您的位置:首页 > 产品设计 > UI/UE

Count Numbers with Unique Digits——Difficulty:Medium

2016-11-14 15:22 337 查看

Problem :

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])


**

Algorithm:

**

可以把n看成位数,设F(k)表示k位数中有多少个数是符合条件的,那么我们要求得结果就变成了F(k)+F(k-1)+F(k-2)+……+F(1),而F(k)=9*9*8*……(9-k+2)

**

Code:

class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if(n==0)
return 1;
if(n==1)
return 10;
int a=10;
for(int j=2;j<=n;j++)
{
int sum=9;
for(int i=2;i<=j;i++)
{
sum*=11-i;
}
a+=sum;
}
return a;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: