给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n。
示例:
给定 n = 2,返回 91。(答案应该是除[11,22,33,44,55,66,77,88,99]
外,0 ≤ x < 100 间的所有数字)
思路:
利用排列组合思想,只考虑n位不重复的序列。
1.n位中不含0的所有排列个数:在9个数字中取n个进行排列,A(9,n)
2.n位中含一个0的所有排列:C(9,n-1)*A(n,n)=n*A(9,n-1)
.
.
.
3.含n-1个0:C(9,1)*A(2,2)
4.含n位0,即等于0:C(9,0)*A(1,1)=1
累加即为答案。
java代码如下:
class Solution {
public int countNumbersWithUniqueDigits(int n) {
int ans=0;
int temp=1;
int jishu=9;
int i=n;
while(i!=0)
{
temp*=jishu--;
i--;
}
ans+=temp;
while(n!=0)
{ temp=1;
jishu=9;
i=n-1;
while(i--!=0)
{
temp*=jishu--;
}
ans+=(n*temp);
n--;
}
return ans;
}
}
执行时间:0ms