|
2 | 2 | # Space: O(n)
|
3 | 3 |
|
4 | 4 | class Solution(object):
|
5 |
| - lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'} |
6 |
| - |
7 |
| - # @param {integer} n |
8 |
| - # @return {string[]} |
9 | 5 | 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 |
11 | 15 |
|
12 |
| - def findStrobogrammaticRecu(self, n, k): |
13 |
| - if k == 0: |
14 |
| - return [''] |
15 |
| - elif k == 1: |
16 |
| - return ['0', '1', '8'] |
17 | 16 |
|
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 |
23 | 37 |
|
24 |
| - return result |
| 38 | + return findStrobogrammaticRecu(n, n) |
25 | 39 |
|
0 commit comments