0%

Coin Change

Given an integer array coins representing coins of different denominations and integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of coins, return −1.

Example:

1
2
3
4
Input: coins = [1, 2, 5], amount = 11;
Output: 3;
Input: coins = [2], amount = 3;
Output: -1;

Constraints:

  • 1 ≤ lcoins ≤ 12
  • 1 ≤ coinsi ≤ 231 − 1
  • 0 ≤ amount ≤ 104

Solution

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

Explanation:

dpi represents the minimum number of coins that makes up the amount i. Assume that the values from dp0 to dpi − 1 are already known, thus the transition equation of dpi can be deduced as dpi = minj = 0lcoins − 1dpi − coinsj + 1 which means the value of dpi is determined by dpi − coinsj. If dpi can transfer from dpi − coinsj via coinsj, the number of coins that used should add 1.