LeetCode | 357. Count Numbers with Unique Digits 数论

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

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

Credits:
Special thanks to 
@memoryless for adding this problem and creatingall test cases.

这一题给你一个n,问你0 <= x <10^n范围内的每一位数字都不相同的数有多少个,

现在我们将0除外

当数字为1位时,这样的数共有m(1) = 9个

当数字为2位时,这样的数共有m(2) = 9* 9个

当数字为3位时,这样的数共有m(3) = 9 *9 * 8个

当数字为4位时,这样的数共有m(4) = 9* 9 * 8 * 7个

。。。

当数字为10位时,这样的数共有m(10)= 9* 9 * 8* 7…* 2 * 1个

然后当数字大于10位时,这样的数字为0个

因此,对于n而言,数字共有m(1) + m(2)+…m(min(10,n))个

可以知道,最多有10种不同的值,所以,我们可以事先打一个表,然后根据输入n直接输出不同的结果即可,记住最后结果需要加1,也就是把0算进来

class Solution(object):
    def countNumbersWithUniqueDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        theNum = [0, 9, 90, 738, 5274, 32490, 168570, 712890, 2345850, 5611770, 8877690]
        if n > 10:  return theNum[10]
        return theNum[n] + 1

猜你喜欢

转载自blog.csdn.net/u012737193/article/details/80157519