直接用昨天的完全背包推导公式,还是很简单的。
322. 零钱兑换
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<int> dp(amount + 1, 1e9);
dp[0] = 0;
for (int i = 0; i < n; i ++)
{
for (int j = coins[i]; j <= amount; j ++)
{
dp[j] = min(dp[j], dp[j - coins[i]] + 1);
}
}
return dp[amount] == 1e9 ? -1 : dp[amount];
}
};
279. 完全平方数
class Solution {
public:
// 先把是平方数的存到n
int numSquares(int n) {
vector<int> arrays;
for (int i = 1; i * i <= n; i ++)
arrays.push_back(i * i);
vector<int> dp(n + 1, 1e9);
dp[0] = 0;
for (int i = 0; i < arrays.size(); i ++)
for (int j = arrays[i]; j <= n; j ++)
dp[j] = min(dp[j], dp[j - arrays[i]] + 1);
return dp[n];
}
};