lc-279


/**
Given an integer n, return the least number of perfect square numbers that sum 
to n. 

 A perfect square is an integer that is the square of an integer; in other 
words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 
are perfect squares while 3 and 11 are not. 

 
 Example 1: 

 
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
 

 Example 2: 

 
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
 

 
 Constraints: 

 
 1 <= n <= 10⁴ 
 
 Related Topics广度优先搜索 | 数学 | 动态规划 

 👍 1504, 👎 0 

*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n + 1];

        dp[1] = 1;

        List<Integer> squareList = new ArrayList<>();

        int i = 1;

        while (i * i < 10000) {
            squareList.add(i * i);
            i++;
        }

        for (i = 2; i <= n; i++) {
            int min = 10000;

            for (int j = 0; j < squareList.size(); j++) {
                if (i - squareList.get(j) < 0) {
                    break;
                }

                if (dp[i - squareList.get(j)] + 1 < min) {
                    min = dp[i - squareList.get(j)] + 1;
                }
            }

            dp[i] = min;
        }

        return dp[n];
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !