-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdigits_sum.py
executable file
·74 lines (59 loc) · 1.49 KB
/
digits_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/python
"""
Given two integers 'n' and 'sum', find count of all n digit numbers with sum of digits
as 'sum'. Leading 0's are not counted as digits. Return -1 if not possible.
http://www.geeksforgeeks.org/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/
"""
def digits_sum(n, target_sum, cur):
if n == 0:
if target_sum == 0 and cur[0] != 0:
return 1
else:
return 0
count = 0
for i in range(10):
if i <= target_sum:
cur.append(i)
count += digits_sum(n-1, target_sum-i, cur)
cur.pop()
return count
def recursive(n, target_sum):
"""
>>> recursive(2, 2)
2
>>> recursive(2, 5)
5
>>> recursive(3, 6)
21
"""
print digits_sum(n, target_sum, [])
def digits_sum_memo(n, target_sum, cur, memo):
if n == 0:
if target_sum == 0 and cur[0] != 0:
return 1
else:
return 0
if memo.get((n, target_sum)):
return memo[(n, target_sum)]
count = 0
for i in range(10):
if i <= target_sum:
cur.append(i)
count += digits_sum_memo(n-1, target_sum-i, cur, memo)
cur.pop()
memo[(n, target_sum)] = count
return count
def dp(n, target_sum):
"""
>>> dp(2, 2)
2
>>> dp(2, 5)
5
>>> dp(3, 6)
21
"""
memo = dict()
print digits_sum_memo(n, target_sum, [], memo)
if __name__ == "__main__":
import doctest
doctest.testmod()