[leetcode]Strobogrammatic Number II

Posted 阿牧遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]Strobogrammatic Number II相关的知识,希望对你有一定的参考价值。

python3

先对左边进行backtrace,然后根据奇偶添加右边的。

class Solution:
    def findStrobogrammatic(self, n: int) -> List[str]:
        if n == 0:
            return []
        
        charDict = {‘0‘: ‘0‘, ‘1‘: ‘1‘, ‘6‘: ‘9‘, ‘8‘: ‘8‘, ‘9‘: ‘6‘}
        lst = []
        
        self.backtrace(n // 2, ‘‘, lst)
        
        result = []
        
        for item in lst:
            reverse = ‘‘
            for i in range(len(item)):
                reverse += charDict[item[len(item) - i - 1]]
            if n % 2 == 0:
                result.append(item + reverse)
            else:
                result.append(item + ‘0‘ + reverse)
                result.append(item + ‘1‘ + reverse)
                result.append(item + ‘8‘ + reverse)
        return result
                
        
    def backtrace(self, m: int, current: str, lst: List[str]):
        if len(current) == m:
            lst.append(current)
            return
        for char in [‘0‘, ‘1‘, ‘6‘, ‘8‘, ‘9‘]:
            if (current + char)[0] == ‘0‘:
                continue
            self.backtrace(m, current + char, lst)

  

以上是关于[leetcode]Strobogrammatic Number II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Strobogrammatic Number 对称数

Leetcode 246: Strobogrammatic Number

[LeetCode] Strobogrammatic Number III 对称数之三

[LeetCode] Strobogrammatic Number III

[LeetCode] 246. Strobogrammatic Number 对称数

[LeetCode] Strobogrammatic Number II