[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)