[leetcode] 357. Count Numbers with Unique Digits

本文探讨了如何计算在指定范围内,所有位数上的数字都各不相同的整数的数量。通过使用动态规划方法,我们找到了一种有效的方式,即通过递推公式f(k)=9*9*8*…(9-k+2)来解决这个问题。文章详细解释了通项公式的由来,并给出了完整的C++代码实现。

Description

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:

Input: 2
Output: 91 
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 
             excluding 11,22,33,44,55,66,77,88,99

分析

题目的意思是:找一个范围内的各位上不相同的数字,比如123就是各位不相同的数字,而11,121,222就不是这样的数字。

  • 一位数的满足要求的数字是10个(0到9)
  • 二位数的满足题意的是81个,[10 - 99]这90个数字中去掉[11,22,33,44,55,66,77,88,99]这9个数字,还剩81个
  • 通项公式为f(k) = 9 * 9 * 8 * … (9 - k + 2),那么我们就可以根据n的大小,把[1, n]区间位数通过通项公式算出来累加起来即可.

dp[0] = 1
dp[1] = 9x9 + dp[0]
dp[2] = 9x9x8 + dp[1]
dp[3] = 9x9x8x7 + dp[2]

代码

class Solution {
public:
    int countNumbersWithUniqueDigits(int n) {
        vector<int> dp(n+1,0);
        dp[0]=1;
        for(int i=1;i<=n;i++){
            dp[i]=dp[i-1]+9*factorial(i-1);
        }
        return dp[n];
    }
    int factorial(int n){
        int res=1;
        for(int i=0;i<n;i++){
            res=res*(9-i);
        }
        return res;
    }
};

参考文献

357. Count Numbers with Unique Digits
[LeetCode] Count Numbers with Unique Digits 计算各位不相同的数字个数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值