Skip to content

Commit a411039

Browse files
authored
Update strobogrammatic-number-ii.py
1 parent 0f55565 commit a411039

File tree

1 file changed

+30
-16
lines changed

1 file changed

+30
-16
lines changed

Python/strobogrammatic-number-ii.py

+30-16
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,38 @@
22
# Space: O(n)
33

44
class Solution(object):
5-
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
6-
7-
# @param {integer} n
8-
# @return {string[]}
95
def findStrobogrammatic(self, n):
10-
return self.findStrobogrammaticRecu(n, n)
6+
"""
7+
:type n: int
8+
:rtype: List[str]
9+
"""
10+
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
11+
result = ['0', '1', '8'] if n%2 else ['']
12+
for i in xrange(n%2, n, 2):
13+
result = [a + num + b for a, b in lookup.iteritems() if i != n-2 or a != '0' for num in result]
14+
return result
1115

12-
def findStrobogrammaticRecu(self, n, k):
13-
if k == 0:
14-
return ['']
15-
elif k == 1:
16-
return ['0', '1', '8']
1716

18-
result = []
19-
for num in self.findStrobogrammaticRecu(n, k - 2):
20-
for key, val in self.lookup.iteritems():
21-
if n != k or key != '0':
22-
result.append(key + num + val)
17+
# Time: O(n * 5^(n/2))
18+
# Space: O(n)
19+
class Solution2(object):
20+
def findStrobogrammatic(self, n):
21+
"""
22+
:type n: int
23+
:rtype: List[str]
24+
"""
25+
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
26+
def findStrobogrammaticRecu(n, k):
27+
if k == 0:
28+
return ['']
29+
elif k == 1:
30+
return ['0', '1', '8']
31+
result = []
32+
for num in findStrobogrammaticRecu(n, k - 2):
33+
for key, val in lookup.iteritems():
34+
if n != k or key != '0':
35+
result.append(key + num + val)
36+
return result
2337

24-
return result
38+
return findStrobogrammaticRecu(n, n)
2539

0 commit comments

Comments
 (0)