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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值