-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-no-zero-pairs-that-sum-to-n.py
More file actions
60 lines (57 loc) · 2.15 KB
/
count-no-zero-pairs-that-sum-to-n.py
File metadata and controls
60 lines (57 loc) · 2.15 KB
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
# Time: O(10 * 2^4 * logn)
# Space: O(2^3)
# dp
class Solution(object):
def countNoZeroPairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)] # dp[carry][a is finished][b is finished]
dp[0][0][0] = 1
start = 1
while n:
n, d = divmod(n, 10)
new_dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)]
for c in xrange(2):
for i in xrange(2):
for j in xrange(2):
if not dp[c][i][j]:
continue
for x in xrange(start, (9 if not i else 0)+1):
for nc in xrange(2):
y = (d+nc*10)-(c+x)
if not (start <= y <= (9 if not j else 0)):
continue
new_dp[nc][i or not x][j or not y] += dp[c][i][j]
start = 0
dp = new_dp
return sum(dp[0][i][j] for i in xrange(2) for j in xrange(2))
# Time: O(10^2 * 2^3 * logn)
# Space: O(2^3)
# dp
class Solution2(object):
def countNoZeroPairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)] # dp[carry][a is finished][b is finished]
dp[0][0][0] = 1
start = 1
while n:
n, d = divmod(n, 10)
new_dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)]
for c in xrange(2):
for i in xrange(2):
for j in xrange(2):
if not dp[c][i][j]:
continue
for x in xrange(start, (9 if not i else 0)+1):
for y in xrange(start, (9 if not j else 0)+1):
if (c+x+y)%10 != d:
continue
new_dp[(c+x+y)//10][i or not x][j or not y] += dp[c][i][j]
start = 0
dp = new_dp
return sum(dp[0][i][j] for i in xrange(2) for j in xrange(2))