leetcode_357 Count Numbers with Unique Digits
2028 ワード
i = 1 ,10
i = 2 ,10 + 9*9
i = 3 ,10 + 9*9 + 9*9*8
i = 4 ,10 + 9*9 + 9*9*8 + 9*9*8*7
......
i = n ,10 + 9*9 + 9*9*8 + 9*9*8*7 + ... + 9*9*8*7*...*(9-i+2)
以上の分析に基づいて、プログラムを作成して実現することができる.//
int countNumbersWithUniqueDigits1(int n)
{
if (n == 0)
return 1;
int result = 10;
if (n == 1)
return result;
int temp = 9;
for (int i = 2; i <= n; i++)
{
temp = temp * (9 - i + 2);
result += temp;
}
return result;
}
// ( )
int countNumbersWithUniqueDigits(int n)
{
n = min(n, 10);
int *p = new int[n+1];
for (int i = 0; i <= n; i++)
{
p[i] = 9;
}
p[0] = 1;
for (int i = 2; i <= n; i++)
{
for (int x = 9; x >= 9 - i + 2; x--)
{
p[i] *= x;
}
}
int result = 0;
for (int i = 0; i <= n; i++)
result += p[i];
return result;
}
//
public int countNumbersWithUniqueDigits(int n) {
if (n == 0)
return 1;
if (n == 1)
return 10;
int result = 10;
int temp = 9;
for (int i = 2; i <= n; i++) {
temp *= (9 - i + 2);
result += temp;
}
return result;
}
// ( )
public int countNumbersWithUniqueDigits(int n) {
if (n == 0)
return 1;
if (n == 1)
return 10;
int [] p = new int[n + 1];
for (int i = 0; i <= n; i++)
p[i] = 9;
int result = 0;
p[0] = 1;
for (int i = 2; i <= n; i++) {
for (int x = 9; x >= 9 - i + 2; x--) {
p[i] *= x;
}
}
for (int i = 0; i <= n; i++) {
result += p[i];
}
return result;
}