forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
67 lines (50 loc) · 1.38 KB
/
main2.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
/// Source : https://leetcode.com/problems/coin-change/solution/
/// Author : liuyubobobo
/// Time : 2018-03-08
#include <iostream>
#include <vector>
using namespace std;
/// Dynamic Problem
/// 0-1 backpack problem
///
/// Time Complexity: O(coins_size * amount)
/// Space Complexity: O(amount)
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, amount + 1);
dp[0] = 0;
for(int coin: coins)
for( int j = coin ; j <= amount ; j ++ )
if( dp[j - coin] != -1 )
dp[j] = min( dp[j], dp[j-coin] + 1);
return dp[amount] == amount + 1 ? -1 : dp[amount];
}
};
int main() {
vector<int> coins1 = {1, 2, 5};
int amount1 = 11;
cout<< Solution().coinChange(coins1, amount1) << endl;
// 3
// ---
vector<int> coins2 = {2};
int amount2 = 1;
cout << Solution().coinChange(coins2, amount2) << endl;
// -1
// ---
vector<int> coins3 = {2};
int amount3 = 3;
cout << Solution().coinChange(coins3, amount3) << endl;
// -1
// ---
vector<int> coins4 = {2, 5, 10, 1};
int amount4 = 27;
cout << Solution().coinChange(coins4, amount4) << endl;
// 4
// ---
vector<int> coins5 = {186, 419, 83, 408};
int amount5 = 6249;
cout << Solution().coinChange(coins5, amount5) << endl;
// 20
return 0;
}