LeetCode 279. Perfect Squares

Given a positive integer n, find the **least number of perfect square numbers (**for example, 1, 4, 9, 16, …) which sum to n.

first time you met with this, there is no way that i’m thinking that as something can be solved in DP.

dp[i]: least number of square to form the number i
dp[i] = dp[j] + dp[i - j] (j from 1 to i-1).
and the intialize of dp[] is very tricky and important.
so after a while, i came up with this, it’s working but the complexity is very bad;

public class Solution {
    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++) {
            if (Math.sqrt(i)%1 == 0) {
                dp[i] = 1;
            }
        }
        
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i] = Math.min(dp[i], dp[j] + dp[i-j]);
            }
        }
        return dp[n];
        
    }
}

在这里插入图片描述
but there is some way you can do it much faster

public class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n+1];
        Arrays.fill(dp, Integer.MAX_VALUE); //because we choose min everytime, so we filled array with max
        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); //level number
            }
        }
        return dp[n];
    }
}//dp[i] means the min number of number that can form i
posted @ 2020-11-22 10:25  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报