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

For example, given n=12, return3because12 = 4 + 4 + 4; given n=13, return2because13 = 4 + 9.

Solution: dp[i] = Math.min(dp[i], dp[i - j * j] + 1);

    public int numSquares(int n) {
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            //对每个i,最多有i个, 1^2 + 1^2 +...
            dp[i] = i;
            for (int j = 1; j * j <= i; j++) {     
                dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
            }
        }
        return dp[n];
    }

results matching ""

    No results matching ""