Skip to content

Commit 5b9c9ee

Browse files
committed
added Coin Change 2
1 parent 6c0964d commit 5b9c9ee

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Dynamic Programming/Coin_Change.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
long countWaysToMakeChangeUtil(vector<int>& arr,int ind, int T, vector<vector<long
6+
>>& dp){
7+
8+
if(ind == 0){
9+
return (T%arr[0]==0);
10+
}
11+
12+
if(dp[ind][T]!=-1)
13+
return dp[ind][T];
14+
15+
long notTaken = countWaysToMakeChangeUtil(arr,ind-1,T,dp);
16+
17+
long taken = 0;
18+
if(arr[ind] <= T)
19+
taken = countWaysToMakeChangeUtil(arr,ind,T-arr[ind],dp);
20+
21+
return dp[ind][T] = notTaken + taken;
22+
}
23+
24+
25+
long countWaysToMakeChange(vector<int>& arr, int n, int T){
26+
27+
vector<vector<long>> dp(n,vector<long>(T+1,-1));
28+
return countWaysToMakeChangeUtil(arr,n-1, T, dp);
29+
}
30+
31+
int main() {
32+
33+
vector<int> arr ={1,2,3};
34+
int target=4;
35+
36+
int n =arr.size();
37+
38+
cout<<"The total number of ways is " <<countWaysToMakeChange(arr,n,target);
39+
}
40+
41+
/*
42+
Output:
43+
44+
The total number of ways is 4
45+
46+
Time Complexity: O(N*T)
47+
48+
Reason: There are N*W states therefore at max ‘N*T’ new problems will be solved.
49+
50+
Space Complexity: O(N*T) + O(N)
51+
52+
Reason: We are using a recursion stack space(O(N)) and a 2D array ( O(N*T)).
53+
*/
54+
55+
//contributed by Sourav Naskar

0 commit comments

Comments
 (0)