1. 程式人生 > 程式設計 >詳解ES9的新特性之非同步遍歷Async iteration

詳解ES9的新特性之非同步遍歷Async iteration

題目:

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

給你一個整數 n ,返回和為 n 的完全平方數的 最少數量 。

完全平方數 是一個整數,其值等於另一個整數的平方;換句話說,其值等於一個整數自乘的積。例如,1、4、9 和 16 都是完全平方數,而 3 和 11 不是。

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/perfect-squares

方法一(常規方法):動態規劃

狀態轉移方程:ƒ[i] = 1 + [√i] min j=1ƒ[i-j2]

 1
public int numSqu(int n){ 2 int [] f = new int [n+1]; 3 for (int i=1; i <=n;i++){ 4 int minn = Integer.MAX_VALUE; 5 for(int j = 1; j * j <= i ; j++){ 6 minn = Math.min(minn,f[i - j * j]); 7 } 8 f[i] = minn + 1; 9 } 10 return f[n];
11 } 12 }

方法二:用數學定理來簡化

利用四平方和定理來快速篩選答案

當n≠4k x (8m+7)時,我們需要判斷到底多少個完全平方數能夠表示 n,我們知道答案只會是 1,2,3中的一個:

答案為 1 時,則必有 n 為完全平方數,這很好判斷;

答案為 2 時,則有 n=a2+b2,我們只需要列舉所有的a(1≤a≤√n),判斷 n-a2是否為完全平方數即可;

答案為 3 時,我們很難在一個優秀的時間複雜度內解決它,但我們只需要檢查答案為 1或 2 的兩種情況,即可利用排除法確定答案。

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/perfect-squares/solution/wan-quan-ping-fang-shu-by-leetcode-solut-t99c/

 1 public int numSqu(int n){
 2     if (isPerSqu(n)){
 3         return 1;
 4     }
 5     if (checkAns4(n)){   
 6         return 4;
 7     }
 8     for (int i =1; i * i < n;i++){
 9         int j = n - i*i ;
10         if(isPerSqu(j)){
11             return 2;
12         }
13     }
14     return 3;
15 }
16 
17     public boolean isPerSqu(int x) {
18         int y = (int) Math.sqrt(x);
19         return y*y == x;
20     }
21 
22     public boolean checkAns4(int x){
23         while (x % 4 ==0) {
24             x /= 4;
25         }
26         return x % 8 == 7;
27     }