Google面试题 | 数字计数

本文介绍了一种使用动态规划的方法来解决LeetCode上的题目“计数唯一数字组合”。该问题要求计算所有包含不同数字的非负整数的数量,其中0≤x<10^n。文章提供了详细的算法实现思路,并给出了C++代码示例。

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

Description

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

Solution

题目给了两种解法:回溯搜索和DP,这里用DP方程解决:
f(k) 为k个不等数字组成的数的个数,则有
f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (11 - k) [第一个因子为0是因为非0数不能以0开头]
利用上面的递推式,提前计算好答案存在数组中直接返回,需要注意对n大于10的处理

Code

class Solution {
private:
    int f[11];
public:
    Solution() {
        f[0] = 1; f[1] = 10;
        int t = 9, cnt = 9;
        for (int i=2; i<=10; i++) {
            cnt *= t--;
            f[i] = f[i-1] + cnt;
        }
    }

    int countNumbersWithUniqueDigits(int n) {
        if (n > 10) n = 10;
        return f[n];
    }
};

LeetCode: 357. Count Numbers with Unique Digits

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值