Simple Python Recursive Solution (Explained)


  • 0
    S

    Recurrence relation listed in docstring of method

    class Solution(object):
        def countNumbersWithUniqueDigits(self, n):
            '''
            n = 0 -> 1
            n = 1 -> 9 + countNumbersWithUniqueDigits(0) -> 10
            n = 2 -> 9 * 9 * 8 + countNumbersWithUniqueDigits(1) -> 739
            n = 3 -> 9 * 9 * 8 * 7 + countNumbersWithUniqueDigits(1) -> 5275
            '''
            if n == 0:
                return 1
            else:
                uniques = 9
                if range(9,10-n,-1):
                    uniques *= reduce(lambda x,y:x*y, range(9,10-n,-1)) 
                return uniques + self.countNumbersWithUniqueDigits(n-1)
    

Log in to reply
 

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