File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+ // /Coin Change Problem
5
+ // /Top Down DP
6
+ int dp[100 ] = {0 };
7
+ int coinWaysTD (int amt,int coins[],int n){
8
+ if (amt==0 ){
9
+ dp[0 ] = 1 ;
10
+ return 1 ;
11
+ }
12
+ // /Recursive Case
13
+ int ans = 0 ;
14
+
15
+ if (dp[amt]!=0 ){
16
+ return dp[amt];
17
+ }
18
+ for (int i=0 ;i<n;i++){
19
+ if (amt-coins[i]>=0 ){
20
+ ans += coinWaysTD (amt-coins[i],coins,n);
21
+ }
22
+ }
23
+ // /Store and return for the first time
24
+ dp[amt] = ans;
25
+ return ans;
26
+ }
27
+
28
+ // /Bottom Up DP
29
+ int coinWaysBU (int amt,int coins[],int n){
30
+ int dp[100 ] = {0 };
31
+ dp[0 ] = 1 ;
32
+
33
+ for (int i=1 ;i<=amt;i++){
34
+ for (int j=0 ;j<n;j++){
35
+ if (i-coins[j]>=0 ){
36
+ dp[i] += dp[i-coins[j]];
37
+ }
38
+ }
39
+ }
40
+ return dp[amt];
41
+ }
42
+
43
+
44
+ int main (){
45
+
46
+ int coins[] = {1 ,2 ,3 ,8 };
47
+ int amount = 3 ;
48
+ cout<<coinWaysTD (amount,coins,4 )<<endl;
49
+ cout<<coinWaysBU (amount,coins,4 )<<endl;
50
+ return 0 ;
51
+ }
You can’t perform that action at this time.
0 commit comments