LeetCode[357] Count Numbers with Unique Digits

来源:互联网 发布:linux 内存使用率计算 编辑:程序博客网 时间:2024/05/19 03:45

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

每一次都是最高位不为0的情况加上前一次的结果

class Solution {public:    int countNumbersWithUniqueDigits(int n) {        if (n == 0) return 1;        else if (n > 10) return countNumbersWithUniqueDigits(10);        else        {            int cnt = 9;            for (int i = 0; i < n - 1; i++)                cnt *= (9 - i);            return cnt + countNumbersWithUniqueDigits(n - 1);        }    }};
0 0