1. 程式人生 > >LeetCode學習記錄(3)----完全平方數

LeetCode學習記錄(3)----完全平方數

給定正整數 n,找到若干個完全平方數(比如 1, 4, 9, 16, ...)使得它們的和等於 n。你需要讓組成和的完全平方數的個數最少。

示例 1:

輸入: n = 12
輸出: 3 
解釋: 12 = 4 + 4 + 4.

示例 2:

輸入: n = 13
輸出: 2
解釋: 13 = 4 + 9.

解題思路:將n拆成兩個平方和,當無法滿足時候,拆成一個平方和一個非平方的和。將非平方放入佇列,等待下一輪的拆解。


	public int numSquares(int n) {
		int count=0;
		Queue<Integer> q=new LinkedList<>();
		if(isSqrt(n)) {//n是平方和
			return 1;
		}
		q.offer(n);
		while(!q.isEmpty()) {
			int len=q.size();
			for(int i=0;i<len;i++) {//得到當前層佇列長度
				int top=q.poll();
				for(int j=1;j<=Math.sqrt(top);j++) {
					int m=top-j*j;
					if(isSqrt(m)) {//判斷減去後的數是否是平方數
						count=count+2;
						return count;
					}
					//如果m不是平方數,放入佇列中,等待下一輪的檢測。
					q.offer(m);
				}	
			}
			//當前層佇列沒有滿足條件,下一層迴圈。
			count++;
		}
		return count; 
    }
	





	public static boolean isSqrt(int n) {
		int sqrt = (int) Math.sqrt(n);
		if(sqrt*sqrt==n) {
			return true;
		}
		return false;
	}






	public static int[] calculatePows(int borden) {
		// TODO Auto-generated method stub
		int[] pows=new int[borden];
		for(int i=0;i<borden;i++) {
			pows[i]=(int) Math.pow(i+1, 2);
		}
		return pows;
	}


	public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int n = Integer.parseInt(line);
            
            int ret = new 完全平方數().numSquares(n);
            
            String out = String.valueOf(ret);
            
            System.out.print(out);
        }
    }


感謝下面的參考連結的大佬: