Skip to content

Latest commit

 

History

History
49 lines (33 loc) · 1.34 KB

279-perfect-squares.md

File metadata and controls

49 lines (33 loc) · 1.34 KB

279. Perfect Squares - 完全平方数

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

示例 1:

输入: n = 12
输出: 3 
解释: 12 = 4 + 4 + 4.

示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.

题目标签:Breadth-first Search / Math / Dynamic Programming

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 96 ms 864.3 KB
class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for (int i = 1; i <= n; ++i) {
            for (int j = (int)sqrt(i); j >= 1; --j) {
                dp[i] = min(dp[i], 1 + dp[i - j * j]);
            }
        }
        return dp[n];
    }
};