题解
Medium
Dynamic Programming
顺利做出来了。说明还是理解了coin的组合方式的。动态规划问题,很多都是排列组合问题的应用。
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// dp[i]: with coins combine to amount of i
// dp[i] = dp[k] + dp[i-k]
vector<int> dp(amount+1, -1);
dp[0] = 0;
unordered_set<int> s(coins.begin(), coins.end());
for(int i = 1; i < amount+1; i++) {
for(int coin : coins) {
if(i >= coin) {
if(dp[i-coin] == -1) continue;
if(dp[i] == -1) {
dp[i] = 1 + dp[i-coin];
}
else {
dp[i] = min(dp[i], 1 + dp[i - coin]);
}
}
}
}
return dp[amount];
}
};