-
Notifications
You must be signed in to change notification settings - Fork 105
/
Coin Change 2.cpp
100 lines (84 loc) · 2.42 KB
/
Coin Change 2.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
93
94
95
96
97
98
99
#include<bits/stdc++.h>
using namespace std;
// Notes
// Find the maximum no. of ways to make that amount using the multiple instances of the coins Unbounded Knapsack
// Recursive Approach
int coinChange(vector<int>& coins, int n, int amount)
{
if(n==0)
return 0;
if(amount == 0)
{
return 1;
}
if(coins[n-1] > amount)
{
return coinChange(coins, n-1, amount);
}
return coinChange(coins, n, amount-coins[n-1]) + coinChange(coins, n-1, amount);
}
int change(int amount, vector<int>& coins) {
int n = coins.size();
if(amount == 0) {
return 1;
}
if(n==0)
return 0;
return coinChange(coins, n, amount);
}
// Memoization Top Down Approach
vector<vector<int>> dp;
int coinChange(vector<int>& coins, int n, int amount)
{
if(n==0)
return 0;
if(amount == 0)
{
return 1;
}
if(dp[n][amount] != -1)
{
return dp[n][amount];
}
if(coins[n-1] > amount)
{
dp[n][amount] = coinChange(coins, n-1, amount);
return dp[n][amount];
}
dp[n][amount] = coinChange(coins, n, amount-coins[n-1]) + coinChange(coins, n-1, amount);
return dp[n][amount];
}
int change(int amount, vector<int>& coins) {
int n = coins.size();
if(amount == 0) {
return 1;
}
if(n==0)
return 0;
dp.resize(n+2,vector<int>(amount+2,-1));
dp[n][amount] = coinChange(coins, n, amount);
return dp[n][amount];
}
// Bottom Up Approach
int change(int amount, vector<int>& coins) {
int n = coins.size();
vector<vector<int>>dp(n+1, vector<int>(amount+1,-1));
//int dp[n+1][amount+1];
for(int i=0; i<=amount; i++){
dp[0][i] = 0;
}
for(int i=0; i<=n; i++){
dp[i][0]=1;
}
for(int i=1; i<n+1; i++){
for(int j=1; j<amount+1; j++){
if(coins[i-1] <= j){
dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]];
}
else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n][amount];
}