[leetcode-357-Count Numbers with Unique Digits]

时间:2023-03-09 16:01:04
[leetcode-357-Count Numbers with Unique Digits]

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

思路:

思路:

排列组合题。

设i为长度为i的各个位置上数字互不相同的数。

  • i==1 : 1 0(0~9共10个数,均不重复)
  • i==2: 9 * 9 (第一个位置上除0外有9种选择,第2个位置上除第一个已经选择的数,还包括数字0,也有9种选择)
  • i ==3: 9* 9 * 8 (前面两个位置同i==2,第三个位置除前两个位置已经选择的数还有8个数可以用)
  • ……
  • i== n: 9 * 9 * 8 *…… (9-i+2)

需要注意的是,9- i + 2 >0 即 i < 11,也就是i最大为10,正好把每个数都用了一遍。

参考自:https://www.hrwhisper.me/leetcode-count-numbers-unique-digits/

int countNumbersWithUniqueDigits(int n)
{
if (n == )return ;
if (n == )return ;
vector<int>dp(n+,);
n = min(n,);
int cnt = ;
for (int i = ; i <= n;i++)
{
int j = - i;
dp[i] = dp[i - ] * j;
cnt += dp[i];
}
return cnt;
}