LeetCode 357. Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.

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

分析

这道题求在 0 ≤ x < 10^n 范围内各位数不相同的数有多少个,可以分为一位数不同的有多少个,两位数不同的有多少个,三位数不同的有多少个等等,根据提示中所给的公式,1位数字有10个,第k位有f(k) = 9 * 9 * 8 * … (9 – k + 2)个,累加从2位到n位的f(k)的总和,再加上1位的10个数字,即为所求~

class Solution {
public:
    int countNumbersWithUniqueDigits(int n) {
        int t=9,cnt=10;
        if(n==0) return 1;
        else if(n==1) return 10;
        else if(n>10) return 0;
        else 
          for(int i=2;i<=n;i++){
             t*=(9-i+2);
             cnt+=t;
          }
        return cnt;
    }
};
原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061156.html