-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-322
More file actions
48 lines (46 loc) · 1.35 KB
/
LeetCode-322
File metadata and controls
48 lines (46 loc) · 1.35 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Coins 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.
dynamic programming
make sure that dp[i] and dp[i - coins[j]] != -1
dp[i] = min(dp[i], dp[i - coins[j]] + 1)
*/
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int *dp = new int[amount + 1], i, j;
dp[0] = 0;
for(i = 1; i < amount + 1; ++i)
{
dp[i] = -1;
}
for(i = 1; i < amount + 1; ++i)
{
for(j = 0; j < coins.size(); ++j)
{
if(coins[j] <= i)
{
if(dp[i] == -1 && dp[i - coins[j]] == -1)
{
dp[i] == -1;
}
else if(dp[i] == -1)
{
dp[i] = dp[i - coins[j]] + 1;
}
else if(dp[i - coins[j]] == -1)
{
dp[i] = dp[i];
}
else
{
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
}
}
}
}
return dp[amount];
}
};