(Leetcode)357. Count Numbers with Unique Digits (medium)

来源:互联网 发布:算法英文缩写 编辑:程序博客网 时间:2024/04/27 16:00

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

这里不仅仅得包含动态规划的思想,我一开始仅仅考虑如何从n-1位推到n位,发现之间并没有一个简单的公式可以表示出来,后来才直到得结合组合的思想,例如n位的话可以用阶层的方式轻易表达出n位数不同的结果(注意并不完全时阶层,因为最高位不为0),然后加上n-1位的结果就是n位的结果

我的答案:

class Solution {public:    int countNumbersWithUniqueDigits(int n) {        int sum[100] = {};        sum[1] = 10;        for (int i = 2; i <=n; i++) {            sum[i] = 9;            for (int j = 1; j < i; j++) {                sum[i] *= 10 - j;            }            sum[i] += sum[i - 1];        }        return sum[n];    }};int 
0 0
原创粉丝点击