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.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

题目解答

解题思路

动态规划的方法:

初始化将dp数组置为无穷大;令dp[y * y] = 1,其中:y * y <= n
状态转移方程:
dp[x + y * y] = min(dp[x + y * y], dp[x] + 1)

其中:dp [i] 表示凑成i所需的平方和数字的最小个数,并且 x + y * y <= n
算法的部分执行过程:
1 1 + 1*1 1 + 2*2 1 + 3*3
2 2 + 1*1 2 + 2*2 2 + 3*3
3 3 + 1*1 3 + 2*2 3 + 3*3
4 4 + 1*1 4 + 2*2

代码实现

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

你可能感兴趣的:(算法和刷题)