LeetCode: Count Numbers with Unique Digits

来源:互联网 发布:美团众包辅助软件 编辑:程序博客网 时间:2024/06/06 06:41

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

题目意思是计算x中各个位不同的整数个数,其中0 ≤ x < 10

利用组合的知识,假设一个整数有k位,从高到低每个位置如果不重复可以选取的数个数为9*9*8*(9 - k + 2),因为最高位不能为0,其他位均可。

代码:

int countNumbersWithUniqueDigits(int n) {        if (n == 0) return 1;        int len = n;    int uniqueDigits[11];    uniqueDigits[1] = 9;    for (int i = 1; i < 10; ++i) {        uniqueDigits[i + 1] = uniqueDigits[i] * (9 - i + 1);    }        int res = 0;    for (int i = 1; i <= n; ++i) {        res += uniqueDigits[i];    }        return res + 1;    }


1 0
原创粉丝点击