LeetCode279. Perfect Squares

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/88536220

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.

Example 1:

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

Example 2:

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

题目:计算组成和为n所需的最少的平方数。

思路:动态规划,同LeetCode322. Coin Changedp[i]表示组成和为i所需的最少的平方数的个数,通过不同的中间结点j*j,尝试对dp[i]进行松弛。

工程代码下载

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n+1, INT_MAX);
        dp[0] = 0;
        // For each i, it must be the sum of some number (i - j*j)
        // and a perfect square number (j*j).
        for(int i = 1; i <= n; ++i){
            for(int j = 1; j*j <= i; ++j){
                dp[i] = min(dp[i], dp[i-j*j]+1);
            }
        }
        return dp[n];
    }
};

https://leetcode.com/problems/perfect-squares/discuss/71488/Summary-of-4-different-solutions-(BFS-DP-static-DP-and-mathematics)

猜你喜欢

转载自blog.csdn.net/grllery/article/details/88536220