Python recursive solution


  • 0
    A

    We don't want the begining is 0 which is not a valid number so we avoid recurse those cases.

    def findStrobogrammatic(self, n):
        self.ans = []
        self.findStr(n, "", "")
        return self.ans
    
    def findStr(self, n, str1, str2):
        if n == 0:
            self.ans.append(str1 + str2)
            return
        if n == 1:
            self.findStr(0, str1 + '0', str2)
            self.findStr(0, str1 + '1', str2)
            self.findStr(0, str1 + '8', str2)
        else:
            if str1 and str1[0] != '0':
                self.findStr(n-2, str1 + '0', '0' + str2)
            self.findStr(n-2, str1 + '1', '1' + str2)
            self.findStr(n-2, str1 + '6', '9' + str2)
            self.findStr(n-2, str1 + '8', '8' + str2)
            self.findStr(n-2, str1 + '9', '6' + str2)

  • 0
    D
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.