题目
代码(首刷看解析)
动态规划问题,但我一开始没想到的是在纠结要不要用两层循环,一层遍历amount,一层遍历coins,答案果然是这样,还是对自己的想法不太自信。还有记得初始化dp的时候,赋值一个较大的数,因为在循环时需要min比较最小值
这个题的转移方程不容易推理证明,但其实就是 F ( i ) = min j = 0. … n − 1 F ( i − c j ) + 1 F(i)=\min _{j=0 . \ldots n-1} F\left(i-c_{j}\right)+1 F(i)=minj=0.…n−1F(i−cj)+1
这是自底向上的解法,应该还有自顶向下的解法
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount == 0)
return 0;
int n = coins.size();
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(int j = 0; j < n; j++) {
if(coins[j] <= i) {
dp[i] = min(dp[i], dp[i-coins[j]] + 1);
}
}
}
return dp[amount]==amount+1 ? -1 : dp[amount];
}
};
代码(二刷部分看解析)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount == 0)
return 0;
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(auto& coin : coins) {
if(i - coin >= 0) {
dp[i] = min(dp[i], dp[i-coin]+1);
}
}
}
return dp[amount] == amount+1 ? -1 : dp[amount];
}
};
代码(7.22 三刷部分看解析)
几日不刷动态规划,又快恢复出厂设置了
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount == 0)
return 0;
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(int& coin : coins) {
if(i - coin < 0)
continue;
dp[i] = min(dp[i], dp[i-coin]+1);
}
}
return dp[amount] == amount+1 ? -1 : dp[amount];
}
};
代码(8.25 四刷自解)
#include <climits>
class Solution {
public:
int minMoney(vector<int>& arr, int aim) {
if(aim == 0)
return 0;
vector<int> dp(aim+1, aim);
dp[0] = 0;
for(int i = 1; i <= aim; i++) {
for(int& coin : arr) {
if(i - coin >= 0) {
dp[i] = min(dp[i], dp[i-coin] + 1);
}
}
}
return dp[aim] == aim ? -1 : dp[aim];
}
};
代码(9.7 五刷自解)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount == 0)
return 0;
int n = coins.size();
vector<int> dp(amount+1, amount+1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(int& coin : coins) {
if(i - coin < 0) continue;
dp[i] = min(dp[i], dp[i-coin] + 1);
// cout<<i<<" "<<dp[i]<<endl;
}
}
return dp[amount] == amount+1 ? -1 : dp[amount];
}
};