Python recursive solution


  • 0
    B
        def countAndSay(self, n):
            def count(i):
    #             base case for recursion, case = 2 b/c recursive step requires 2 character input
                if i == 1: return "1"
                if i == 2: return "11"
                counter = 1
                res = ""
    #             get previous output
                prev = count(i-1)
                for i in xrange(1, len(prev)):
                    if prev[i] == prev[i-1]:
                        counter += 1
                    else:
                        res += str(counter) + prev[i-1]
                        counter = 1
                return res + str(counter) + prev[len(prev) - 1]
            return count(n)
    

Log in to reply
 

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