leetcode_247 中心对称数 II

143 阅读1分钟

要求

中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。

找到所有长度为 n 的中心对称数。

示例 :

输入:  n = 2
输出: ["11","69","88","96"]

核心代码

class Solution:
    def findStrobogrammatic(self, n: int) -> List[str]:
        record = dict()
        record[1] = ["0","1","8"]
        record[2] = ["11",'69',"88","96"]
        pair = ["00","11",'69',"88","96"]

        if n <= 2:
            return record[n]
        cnt = 3
        while cnt <= n:
            tmp = []
            if (cnt - 1) % 2 == 0:
                for item in record[cnt - 1]:
                    for num in record[1]:
                        tmp.append(item[:len(item)//2] + num + item[len(item)//2:])
            else:
                for item in record[cnt - 2]:
                    for num in pair:
                        tmp.append(item[:len(item)//2] + num + item[len(item)//2:])
            record[cnt] = tmp
            cnt += 1
        return record[n]

image.png

解题思路:观察可得,对于 n - 1 是偶数的解来说,只要在 n - 1的解的每个数中间 加上 0 或 1 或 8 就可以得到 n 的解。对于 n - 1是奇数的解来说,只要在 n - 2 的解的每个数中间加上 00 , 11, 88, 69, 96就可以得到n 的解。后面的结果由前面的数据扩增得到。