[LeetCode] Coin Change

322. Coin Change

You are given coins of different denominations and a total amount of money amount. Write a function to compute 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 the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

  • new solution update 2022.02.20
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, INT_MAX - 1);
dp[0] = 0;
for(int i = 1; i <= amount; i++) {
for(auto c : coins) {
if(c <= i){
dp[i] = min(dp[i], dp[i-c] + 1);
}
}
}
return dp.back() == INT_MAX - 1 ? -1 : dp.back();
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
queue<pair<long, int>> q;
bool v[10001] = {false, };
v[0] = true;
q.push({0, 0});
sort(coins.begin(), coins.end());
coins.erase(upper_bound(coins.begin(), coins.end(), amount),coins.end());

while(!q.empty()) {
auto p = q.front();
q.pop();
for(auto coin : coins) {
if(p.first + coin <= amount && !v[p.first + coin]) {
v[p.first + coin] = true;
q.push({p.first + coin, p.second + 1});
if(p.first + coin == amount)
return p.second + 1;
}
}
}
return amount ? -1 : 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/11/PS/LeetCode/coin-change/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.