Skip to content

Commit 52bd42e

Browse files
authored
Create TheCoinChangeProblem.cpp
1 parent eb4c0dc commit 52bd42e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//The Coin Change Problem
2+
//Given an Array of coins C, and money S, print number of ways to make a change for S
3+
//Eg: A=[1,2] S=4 answer is {1,1,1,1}, {2,2}, {2,1,1} i.e 3 ways
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
const int N = 1e3;
8+
int A[N], n;
9+
int vis[N][N], dp[N][N];
10+
11+
int ways(int pos, int S) {
12+
if(pos == n) return S == 0;
13+
int &ans = dp[pos][S];
14+
if(vis[pos][S]) return ans; vis[pos][S] = 1, ans = 0;
15+
int times = 0;
16+
while(times*A[pos] <= S) ans += ways(pos+1, S-times*A[pos]), times++;
17+
return ans;
18+
}
19+
20+
//Faster than ways function as it causes only two transitions
21+
int fasterWays(int pos, int S) {
22+
if(pos == n) return S == 0;
23+
if(S < 0) return 0;
24+
int &ans = dp[pos][S];
25+
if(vis[pos][S]) return ans; vis[pos][S] = 1, ans = 0;
26+
ans = ways(pos, S-A[pos]) + ways(pos+1, S);
27+
return ans;
28+
}
29+
30+
int main() {
31+
32+
int i, S;
33+
cin >> n >> S;
34+
for(i=0; i<n; i++) cin >> A[i];
35+
cout << fasterWays(0, S) << endl;
36+
return 0;
37+
}

0 commit comments

Comments
 (0)