1.题目描述
中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。
找到所有长度为 n 的中心对称数。
示例 :
输入: n = 2
输出: ["11","69","88","96"]
2.解题思路
- 首先当n为1的时候,直接得到["0","1","8"]
- 当n为2的时候,得到["00","11","69","88","96"],但是由于“00”不是数字,所以得剔除
- 当n为3的时候,其实就是将n为2的结果,中间插入n为1时候的结果,也就是如下所示:
- ["101","111","181","609","619","689",...],只要把最后的结果,前缀为0的去除就可以了
- 所以可以总结出规律,当n大于2的时候,都是将n等于2的结果,中间夹上n-2时的结果,这样就可以使用递归了,其中递归的中间值,可以使用HashMap来暂存。
作者:Andymon
链接:https://leetcode-cn.com/problems/strobogrammatic-number-ii/solution/tong-guo-di-gui-de-suan-fa-zhao-gui-lu-java-by-and/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3.代码实现
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 1:
return ["0","1","8"]
dic = {}
t = self.dfs(n,dic)
res = []
for string in t:
if string[0] != "0":
res.append(string)
return res
def dfs(self,n,dic):
if n in dic:
return dic[n]
elif n == 1:
l = ["0","1","8"]
dic[n] = l
return l
elif n == 2:
# 不要忘记加入“00”
l = ["00","11","69","88","96"]
dic[n] = l
return l
res = []
l1 = self.dfs(2,dic)
l2 = self.dfs(n-2,dic)
for i in range(len(l1)):
for j in range(len(l2)):
res.append(l1[i][0] + l2[j] + l1[i][1])
dic[n] = res
return res