Print Combinations
def coin_change_solutions(coins, S):
N = len(coins)
sols = [[[] for n in xrange(N + 1)] for s in xrange(S + 1)]
for n in range(0, N + 1):
sols[0][n].append([])
for s in range(1, S+1):
for n in range(1, N+1):
without_last = sols[s][n - 1]
if (coins[n - 1] <= s):
with_last = [list(sol) + [coins[n-1]] for sol in sols[s - coins[n - 1]][n]]
else:
with_last = []
sols[s][n] = without_last + with_last
return sols[S][N]
print coin_change_solutions([1,2], 4)
without : we donβt need to use the last coin to make the amount. All coin solutions are found directly by recursing onto solution[s][n-1]. We take all these combinations of coins and copy them to with_last_sols.
: . . sol[s - coins[n - 1]][n]. , . sol coin[n - 1]:
, .
without_last_sols = [[1,1,1,1]]
with_last_sols = [[1,1,2], [2,2]]
without_last_sols + with_last_sols = [[1,1,1,1], [1,1,2], [2,2]]
1 n:
= [1,2,3,4,..., n] - , num , s, p (s).
, p (s) .
, = p (s) = O (2 ^ s). , . , .
: s n.
s n sols[s][n]:
- : O (2 ^ s)
sol[s - coins[n - 1]][n]. O (n) . , O (n Γ 2 ^ s). - : O (2 ^ s)
sol[s][n]. sol O (n) , . O (n Γ 2 ^ s).
, O (s Γ n) Γ O (n2 ^ s + n2 ^ s) = O (s Γ n ^ 2 Γ 2 ^ s).
- O (s Γ n ^ 2 Γ 2 ^ s), s Γ n
, O (2 ^ s) (, [[1, 1, 1, 1], [1, 1, 2], [2, 2]]), (, [1,1,1,1]) O (n) .