279. Perfect Squares

1、題目數組

  一、審題spa

  

  二、分析code

    給出正整數 n,判斷 n 由幾個平方數的和構成。orm

 

2、解答blog

  一、思路three

    方法1、rem

      動態規劃!it

      ①、建立大小爲 n + 1 的數組。其中,初始化時 dp[0] = 0,其餘元素值爲 Integer.Max_VALUE。form

      ②、以後,依次給 dp 從 1 開始的下標元素進行賦值。採用  dp[i] = dp[i - j *j] + 1; 即經過前面的元素值來推斷出後面的元素值。class

      ③、返回 dp[n];

    public int numSquares(int n) {
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j * j <= i; j++) {
                dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
            }
        }
        return dp[n];
    }

 

  方法2、

     Legendre's  四平方定理;

    根據這必定理: 任意一個正整數,能夠用不超過 4 個平方和的數來表示。其中:

    用 1 個平方和表示: n = A * A;

    用 2 個平方和表示: n = A * A + B * B;

    用 4 個平方和表示: n = 4^k*(8*m + 7); 能用這種方式表示;

    用 3 個平方和表示: 其餘。

    public int numSquares2(int n) {
        // If n is a perfect square, return 1.
        if(is_square(n))
            return 1;
        
        // The result is 4 if and only if n can be written in the 
        // form of 4^k*(8*m + 7). Please refer to 
        // Legendre's three-square theorem.
        while((n & 3) == 0) // n%4 == 0  
            n >>= 2;
        
        if((n & 7) == 7)    // n%8 == 7
            return 4;
        
        // Check whether 2 is the result.
        int sqrt_n = (int)Math.sqrt(n);
        for (int i = 1; i <= sqrt_n; i++) {
            if(is_square(n - i * i))
                return 2;
        }
        
        return 3;
    }
    
    public boolean is_square(int n) {
        int sqrt_n = (int)(Math.sqrt(n));
        return sqrt_n * sqrt_n == n; 
    }
相關文章
相關標籤/搜索