leetcode 357. Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])



def fac(m):
        if m==0 or m==1:
            return 1
        return fac(m-1)*m
class Solution(object):
    def __init__(self):
        self.lookup=[]
        self.lookup.append(10)
        for i in xrange(2,10):
            self.lookup.append(fac(9)/fac(10-i)*(i-1)+fac(9)/fac(9-i))
        
    def countNumbersWithUniqueDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n>9:
            return sum(self.lookup)
        if n:
            return sum(self.lookup[0:n])
        return 1


你可能感兴趣的:(数据结构与算法,python)