leetcode 357. Count Numbers with Unique Digits 统计独特编码数组的数量 + 一个很简单的排列组合问题

偏执的太偏执、 2022-06-07 02:45 192阅读 0赞

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

这道题主要是考察所有的digit的唯一性,最简单的就是遍历,但是肯定会超时,仔细想一下,这是一个排列组合问题。

这道题让我们找一个范围内的各位上不相同的数字,比如123就是各位不相同的数字,而11,121,222就不是这样的数字。那么我们根据提示中的最后一条可以知道,一位数的满足要求的数字是10个(0到9),二位数的满足题意的是81个,[10 - 99]这90个数字中去掉[11,22,33,44,55,66,77,88,99]这9个数字,还剩81个。通项公式为f(k) = 9 * 9 * 8 * … (9 - k + 2),那么我们就可以根据n的大小,把[1, n]区间位数通过通项公式算出来累加起来即可,参见代码如下:

代码如下:

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. /*
  4. * 仔细想一下这是一个简单的排列组合问题
  5. * */
  6. class Solution
  7. {
  8. public int countNumbersWithUniqueDigits(int n)
  9. {
  10. if(n<=1)
  11. return (int)Math.pow(10, n);
  12. int count=10,val=9;
  13. for(int i=2;i<=n;i++)
  14. {
  15. val=val*(9+2-i);
  16. count=count+val;
  17. }
  18. return count;
  19. }
  20. /*
  21. * 直接查询肯定是最直接的想法,但是肯定会超时
  22. * */
  23. public int countNumbersWithUniqueDigitsByLoop(int n)
  24. {
  25. if(n<=1)
  26. return (int)Math.pow(10, n);
  27. int count=0;
  28. for(long i=0;i<Math.pow(10, n);i++)
  29. {
  30. char[] array=(""+i).toCharArray();
  31. Set<Character> set=new HashSet<>();
  32. for(int j=0;j<array.length;j++)
  33. set.add(array[j]);
  34. if(set.size()==(""+i).length())
  35. count++;
  36. }
  37. return count;
  38. }
  39. }

下面是C++的做法

其实这是一个排列组合问题

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. class Solution
  20. {
  21. public:
  22. int countNumbersWithUniqueDigits(int n)
  23. {
  24. if (n == 0)
  25. return 1;
  26. int count = 10 , tmp = 9;
  27. for (int i = 2; i <= n; i++)
  28. {
  29. tmp *= (11 - i);
  30. count += tmp;
  31. }
  32. return count;
  33. }
  34. };

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读