-
Notifications
You must be signed in to change notification settings - Fork 82
/
dp_coin_change.cpp
60 lines (56 loc) · 1.13 KB
/
dp_coin_change.cpp
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
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int ans;
int solve(vector<int> &coins, int n, int cnt, vector<int> &dp)
{
if (n == 0)
{
return 0;
}
if (dp[n] != -1)
{
return dp[n];
}
int ans = INT_MAX;
for (int i = 0; i < coins.size(); i++)
{
if (coins[i] > n)
{
continue;
}
int val = solve(coins, n - coins[i], cnt + 1, dp);
if (val < ans)
{
ans = val;
}
}
if (ans != INT_MAX)
{
ans = ans + 1;
}
dp[n] = ans;
return dp[n];
}
int coinChange(vector<int> &coins, int amount)
{
if (amount == 0)
{
return 0;
}
ans = INT_MAX;
vector<int> dp;
for (int i = 0; i <= amount; i++)
{
dp.push_back(-1);
}
solve(coins, amount, 0, dp);
if (dp[amount] == INT_MAX)
{
return -1;
}
return dp[amount];
}
};