題目描述:
357. Count Numbers with Unique Digits
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
其實(shí)這個(gè)題目不怎么需要?jiǎng)討B(tài)規(guī)劃的知識(shí),感覺有點(diǎn)像找規(guī)律填數(shù)字。
可以把題目拆開,先思考固定長度為n的所有數(shù)中有多少個(gè)數(shù)字均不相同的數(shù)。
另之為f[n],可得:
f[1] = 10; (0, 1,2,3,4,5,6,7,8,9)
f[2] = 9 × 9; (9 ×9,可以在1 - 9 中選出一個(gè)數(shù)字為長度為2的數(shù)字的第一位,在0 以及 1 - 9 除去被先前選中的數(shù)字中選出一個(gè)數(shù)字為長度為2的數(shù)字的第二位)
f[3] = 9 × 9 × 8;
f[4] = 9 × 9 × 8 × 7;
f[5] = 9 × 9 × 8 × 7 × 6;
f[6] = 9 × 9 × 8 × 7 × 6 × 5;
......
f[10] = 9 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1;
f[11] = 0;
f[12] = 0;
所以源程序可以這么寫 !
int countNumbersWithUniqueDigits(int n) {
if(n == 0){
return 1;
}else if(n > 10){
return 0;
}
int result = 10;
int uniqueDigits = 9;
int availableNumber = 9;
while(n > 1 && availableNumber > 0){
uniqueDigits *= availableNumber;
res += uniqueDigits;
n -- ;
availableNumber --;
}
return res;
}