翻译:这里就是在一个只有完全平方数,1,4,9,16的集合里面找到和为n的最少的和数,因为值无限取,所以用完全背包。
求最优方案和,最优值,排列组合数三类动态规划是不同的
这里是最优方案和所以加1而不是加n
cpp
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//在nums中取值可重复和为target的最小和数的数量
int main() {
vector<int> nums = { 1,4,9 };
int target = 13;
vector<int>dp(target+1, INT_MAX);
dp[0] = 0;//j==0时没办法把东西放包里
for (auto n : nums)
for (int j = n;j <=target;j++)
{
if(n<=j)
dp[j] = min(dp[j],dp[j - n]+1);//这里是求数量不是求最优值所有加1而不是n
}
for (auto n : dp)
{
cout << n << endl;
}
return 0;
}
答案
cpp
class Solution {
public:
int numSquares(int n) {
int i=1;
int p=i;
vector<int>dp(n+1,INT_MAX/2);
dp[0]=0;
while(p<=n)
{
for(int j=p;j<=n;j++)
{
dp[j]=min(dp[j],dp[j-p]+1);
}
i++;
p=pow(i,2);
}
return dp[n];
}
};