题目描述:
给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n。
示例:
给定 n = 2,返回 91。(答案应该是除[11,22,33,44,55,66,77,88,99]
外,0 ≤ x < 100 间的所有数字)
解题思路:
首先,n可以表示这最大可以是个几位数,比如n=2.说明x的范围是个1~2位的数。(n=0为特殊情况,单独讨论)
然后因为我们知道各位数字都不同的一个i(i>1)位数的个数是9*9*8*7...*(11-i).(i=1这种特殊情况为10种)。
所以这道题就可以转化成求 :各位数字都不同的一个n位数的个数+各位数字都不同的一个n-1位数的个数+各位数字都不同的一个n-2位数的个数+...+各位数字都不同的一个1位数的个数。
代码:
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
x=0;
if n==0:
return 1
for i in range(0,n):
x=x+self.countpart(i)
return x
def countpart(self,n):
if n==0:
return 10
x=9
left=9
while(n>0):
x=x*left
left=left-1
n=n-1
return x