0%

LeetCode 322. Coin Change

题目

原题在此

解析

一道经典的DP题目.

  1. dp[i] = min(dp[i - coins[0]], dp[i - coins[1]] ... dp[i - coins[n]])
  2. dp[0] = 0

代码

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, 10001);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(int j = 0; j < coins.size(); j++) {
if(i - coins[j] >= 0){
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
}
}
}
return dp[amount] == 10001 ? -1 : dp[amount];
}
};