【357】Count Numbers with Unique Digits

本文介绍了一种算法,用于计算在0到10^n-1范围内具有唯一数字的整数数量。通过递归方法和逐步增加位数的方式,文章详细解释了如何高效地求解这一问题,并附带提供了一个C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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为i时,输出结果为res[ i ];

当 n = 0 时,res[ 0 ]=1;

当 n = 1 时,res[ 1 ] = 9 + res[ 0 ];

当 n = 2 时,若该数字为两位数,那么0在个位时有9种情况,没有0时有9*8种情况;再加上该数字为一位数时的情况,即n=1时的情况。

res[ 2 ]= 9 + 9 * 8 + res[ 1 ] = 9 * ( 1 + 8 ) + res[ 1 ];

当 n = 3 时,若该数字为三位数,0在个位时有9*8种情况,0在十位时有9*8种情况,没有0时有9*8*7种情况;再加上n=2时的情况,即为最终结果。

res[ 3 ] = 9 * 8 + 9 * 8 + 9 * 8 * 7 + res[ 2 ] = 9 * 8 * (7+1+1) + res[ 2 ];

可以推出:

当n = 0 时,res[ 0 ]=1;

当n = 1 时,res[ 1 ] = 9 + res[ 0 ];

当n = i ( 1< i <= 10) 时,res[ i ] = 9 * 8 *...* (10 - i + 1 ) * 9 + res[ i - 1 ];

当n > 10 时, res[ n ] = 0;


代码:

class Solution {
public:
    int countNumbersWithUniqueDigits(int n) {
        int c=9;
        int res;
        if(n==0)
            return 1;
        if(n==1)
            return 10;
        if(n>10)
            return 0;
        else {
            for (int i=9;i>10-n;i--) {
                c *= i;    
            }
            res = c + countNumbersWithUniqueDigits(n-1);
            return res;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值