Skip to content

Commit 5456d18

Browse files
committed
tabulated code in python for coin change problem added
1 parent d20ee18 commit 5456d18

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

coin_change.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
DYnamic Programming: Coing Change problem
3+
4+
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.
5+
6+
7+
Input Format:
8+
4
9+
1 2 3
10+
11+
the first line is the change
12+
and second lines contain denominations (D)
13+
14+
Algorithm Strategy:
15+
16+
N(val) = sum{ N(r) + N(val - r) for r in D }
17+
18+
'''
19+
20+
N = int(input())
21+
D = list(map(int, input().split(" ")))
22+
m = {}
23+
24+
def solve(d, Dd):
25+
if (d, len(Dd)) in m:
26+
return m[(d, len(Dd))]
27+
ans = 0
28+
if d == 0:
29+
return 1
30+
if d < 0:
31+
return 0
32+
if len(Dd) <= 0 and d >=1:
33+
return 0
34+
#----no .of ways to get to d using sub arrays + number of ways to get to d-r uring D
35+
ans = solve(d, Dd[:len(Dd)-1]) + solve(d - Dd[len(Dd)-1], Dd)
36+
m[(d, len(Dd))] = ans
37+
return ans
38+
39+
print(solve(4, D))
40+

ip.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
1 5 8 9 10 17 17 20
1+
4
2+
1 2 3

0 commit comments

Comments
 (0)