-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin_change.cpp
More file actions
111 lines (101 loc) · 2.55 KB
/
coin_change.cpp
File metadata and controls
111 lines (101 loc) · 2.55 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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* =====================================================================================
*
* Filename: coin_change.cpp
*
* Description: 322. Coin Change. https://leetcode.com/problems/coin-change/
*
* Version: 1.0
* Created: 04/03/23 10:26:22
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <climits>
#include <tuple>
#include <unordered_map>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace std;
// Dynamic programming, time limit exceeded
class Solution1 {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount < 0) {
return -1;
} else if (amount == 0) {
return 0;
}
int res = INT_MAX;
for (const int c : coins) {
const int sub = coinChange(coins, amount - c);
if (sub == -1) {
continue;
}
res = std::min(res, sub + 1);
}
return (res == INT_MAX ? -1 : res);
}
};
// Dynamic programming + hash table, top down
class Solution2 {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount < 0) {
return -1;
} else if (amount == 0) {
return 0;
}
auto it = nums_.find(amount);
if (it != nums_.end()) {
return it->second;
}
int res = INT_MAX;
for (const int c : coins) {
const int sub = coinChange(coins, amount - c);
if (sub == -1) {
continue;
}
res = std::min(res, sub + 1);
}
if (res == INT_MAX) {
res = -1;
}
nums_[amount] = res;
return res;
}
private:
unordered_map<int, int> nums_;
};
// Dynamic programming, bottom up
class Solution3 {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (const int c : coins) {
if (c <= i) {
dp[i] = std::min(dp[i], 1 + dp[i - c]);
}
}
}
return (dp[amount] == (amount + 1) ? -1 : dp[amount]);
}
};
TEST(Solution, coinChange) {
vector<tuple<vector<int>, int, int>> cases = {
std::make_tuple(vector<int>{1, 2, 5}, 11, 3),
};
for (auto& c : cases) {
EXPECT_EQ(Solution1().coinChange(std::get<0>(c), std::get<1>(c)), std::get<2>(c));
EXPECT_EQ(Solution2().coinChange(std::get<0>(c), std::get<1>(c)), std::get<2>(c));
EXPECT_EQ(Solution3().coinChange(std::get<0>(c), std::get<1>(c)), std::get<2>(c));
}
}