-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path322. Coin Change.cpp
92 lines (60 loc) · 1.68 KB
/
322. 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> s(amount+1, INT_MAX);
s[0] = 0;
for(int i = 1;i<=amount;i++) {
for(int j = 0;j<coins.size();j++) {
if(coins[j]>i)
continue;
if(s[i-coins[j]]!=INT_MAX)
s[i] = min(s[i] , 1+s[i-coins[j]]);
}
}
if(s[amount] == INT_MAX)
s[amount] = -1;
return s[amount];
}
};
-------------------
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(!amount)
return 0;
if(coins.empty())
return -1;
vector<int> s(amount+1, -1);
s[0] = 0;
for(int i = 1; i<= amount; ++i) {
for(int j = 0; j < coins.size(); ++j) {
if (coins[j] <= i) {
if (s[i-coins[j]]!= -1)
s[i] = min( (s[i] == -1? INT_MAX : s[i]) , 1 + s[i-coins[j]] );
}
}
}
return s[amount];
}
};
---------------------------
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(!amount)
return 0;
vector<int> v(amount+1, INT_MAX);
sort(coins.begin(), coins.end());
v[0] = 0;
for(int i = 1;i<=amount; ++i) {
for(int j = coins.size()-1; j>=0 ;--j) {
if(coins[j] <= i && v[i-coins[j]]!=INT_MAX) {
v[i] = min(v[i], 1+ v[i-coins[j]]);
}
}
}
if (v[amount] == INT_MAX)
v[amount] = -1;
return v[amount];
}
};