Leetcode 题目解析之 Perfect Squares

2022-02-28 21:03:39 浏览数 (1)

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.

动态规划,求解最优化问题,自底向上。

代码语言:javascript复制
    public int numSquares(int n) {
        int[] dp = new int[n   1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        // 将所有平方数置1
        for (int i = 0; i * i <= n; i  ) {
            dp[i * i] = 1;
        }
        for (int a = 1; a <= n; a  ) {
            for (int b = 1; a   b * b <= n; b  ) {
                // 取较小值,a   b * b也可能是平方数
                dp[a   b * b] = Math.min(dp[a]   1, dp[a   b * b]);
            }
        }
        return dp[n];
    }

0 人点赞