Python solution with explanation in comment


  • 2
    T
        def countNumbersWithUniqueDigits(self, n):
            # n can not be greater than 10 as it must exist two of the digit share same number
            # f(n) = 1-digits unique num combination + 2-digits unique num combination + ...
            # f(n) = 10 + 9 * 9 + 9 * 9 * 8 + ...
            # f(n) = g(0) + g(1) + g(2) + ... + g(n)
            # g(0) = 10
            # g(1) = 9 * 9
            # g(2) = 9 * 9 * 8
            # g(k) = 9 * (10 - 1) * (10 - 2) * ... * (10 - k)
            if n == 0: return 1
            if n == 1: return 10
            n = min(10, n)
            res = 10
            for n in range(1, n):
                g = 9
                for i in range(1, n+1):
                    g *= (10 - i)
                res += g
            return res
    

Log in to reply
 

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