title: 零钱兑换问题
abbrlink: 5
322零钱兑换问题
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int max1 = amount + 1;
vector<int> dp(amount+1,max1);
dp[0] = 0;
for (int i = 0; i < coins.size(); ++i)
{
for (int j = 1; j <= amount; ++j)
{
if (coins[i] <= j)
{
dp[j] = min(dp[j], dp[j - coins[i]] + 1);
}
}
}
return dp[amount] != max1 ? dp[amount] : -1;
}
};
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < coins.size(); i++) { // 遍历物品
for (int j = coins[i]; j <= amount; j++) { // 遍历背包
if (dp[j - coins[i]] != INT_MAX) { // 如果dp[j - coins[i]]是初始值则跳过
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
}
}
}
if (dp[amount] == INT_MAX) return -1;
return dp[amount];
}
};
标签:背包,int,coins,问题,amount,vector,dp,size
From: https://www.cnblogs.com/penguin3k/p/17997752