动态规划之不同数字组成数的数量

来源:互联网 发布:网络品牌推广 编辑:程序博客网 时间:2024/05/24 04:30

LeetCode 357. Count Numbers with Unique Digits

题目

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个不同的数字排列组合在一起就可以得到相应的数,但是要考虑一种情况就是当第一位是0的时候,这时不能构成一个数字,所以要除掉这种情况,再加上n-1位的数量。关键代码是dp[i] = Amn(i, 10) - Amn(i-1, 9) + dp[i-1];
复杂度分析,空间复杂度和时间复杂度都是O(n)

代码

class Solution {public:    int countNumbersWithUniqueDigits(int n) {        if (n > 10) n = 10;        int* dp = new int[n+1];        dp[0] = 1;        for (int i = 1; i <= n; i++) {            dp[i] = Amn(i, 10) - Amn(i-1, 9) + dp[i-1];        }        int res = dp[n];        delete []dp;        return res;    }    int Amn(int m, int n) {        if (m > n) return 0;        int res = 1;        for (int i = 0; i < m; i++) res *= (n-i);        return res;    }};

题目地址:LeetCode357