Skip to content

Commit b26a7f8

Browse files
committed
Working and in dynamic programming
1 parent 7a0ca2c commit b26a7f8

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

CoinChangeSet1.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#Coin change
2+
#Given a value N, if we want to make change for N cents, and we have infinite supply
3+
#of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change?
4+
#The order of coins doesn’t matter.
5+
6+
#For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}.
7+
#So output should be 4. For N = 10 and S = {2, 5, 3, 6},
8+
#there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.
9+
def createMatrix(n,s):
10+
m = [[0 for col in range(n+1)] for row in range(len(s)+1)]
11+
#Fill first col with 1
12+
for row in range(len(s)+1):
13+
m[row][0] = 1
14+
return m
15+
16+
def foo(n, s):
17+
matrix = createMatrix(n, s)
18+
for row in range(len(s)):
19+
for col in range(n+1):
20+
if(col < s[row]):
21+
#Copy value from the top
22+
matrix[row+1][col] = matrix[row][col]
23+
else:
24+
#add the value from top and s[row] steps behind
25+
matrix[row+1][col] = matrix[row][col]+matrix[row+1][col-s[row]]
26+
print matrix
27+
print "So the total number of ways to make the change is "+str(matrix[len(s)][n])
28+
29+
#Main Program
30+
foo(10, [6, 2, 5, 3])
31+
foo(4, [1,2,3])

0 commit comments

Comments
 (0)