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

【357】Count Numbers with Unique Digits

2017-04-15 21:31 253 查看
题目:

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

思路:

记n为i时,输出结果为res[ i ];

当 n = 0 时,res[ 0 ]=1;

当 n = 1 时,res[ 1 ] = 9 + res[ 0 ];

当 n = 2 时,若该数字为两位数,那么0在个位时有9种情况,没有0时有9*8种情况;再加上该数字为一位数时的情况,即n=1时的情况。

res[ 2 ]= 9 + 9 * 8 + res[ 1 ] = 9 * ( 1 + 8 ) + res[ 1 ];

当 n = 3 时,若该数字为三位数,0在个位时有9*8种情况,0在十位时有9*8种情况,没有0时有9*8*7种情况;再加上n=2时的情况,即为最终结果。

res[ 3 ] = 9 * 8 + 9 * 8 + 9 * 8 * 7 + res[ 2 ] = 9 * 8 * (7+1+1) + res[ 2 ];

可以推出:

当n = 0 时,res[ 0 ]=1;

当n = 1 时,res[ 1 ] = 9 + res[ 0 ];

当n = i ( 1< i <= 10) 时,res[ i ] = 9 * 8 *...* (10 - i + 1 ) * 9 + res[ i - 1 ];

当n > 10 时, res[ n ] = 0;

代码:class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
int c=9;
int res;
if(n==0)
return 1;
if(n==1)
return 10;
if(n>10)
return 0;
else {
for (int i=9;i>10-n;i--) {
c *= i;
}
res = c + countNumbersWithUniqueDigits(n-1);
return res;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: