题目:
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/pe…
分析:
此题可转换为完全背包问题(背包九讲),对于每个平方数都放入数组中,同时取一个平方数的代价为1,我们求达到目标时的最小代价数,最后就能得到最小需要的数的数量
code:
class Solution {
public:
int numSquares(int n) {
vector<int> cost;
vector<int> ans(n+1, 10000);
ans[0] = 0;
for(int i = 1; i <= sqrt(n); i++)
cost.push_back(i*i);
for(int i = 0; i < cost.size(); i++)
{
for(int j = cost[i]; j <= n; j++)
{
ans[j] = min(ans[j], ans[j - cost[i]] + 1);
}
}
return ans[n];
}
};