LeetCode每日一题(1012. Numbers With Repeated Digits)

给定整数n,求[1, n]范围内至少有一个数字重复的正整数个数。例如,当n=20时,结果为1,因为只有11满足条件。通过计算没有重复数字的数的个数来解决问题,分为位数小于n和等于n两种情况,利用位运算和数字组合进行计算。" 76095950,5741891, Realm数据库快速入门与常见问题,"['数据库', 'Android开发', 'Java编程', 'Realm配置', '数据模型']
摘要由CSDN通过智能技术生成

Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.

Example 1:

Input: n = 20
Output: 1

Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.

Example 2:

Input: n = 100
Output: 10

Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.

Example 3:

Input: n = 1000
Output: 262

Constraints:

  • 1 <= n <= 109

整体上我们反过来想, 至少重复 2 位的数字的数量=总数-没有重复数字的数量, 那我们只要算出所有没有重复数字的数量就可以了。这部分我们又可以分为两部分。 一部分是位数小于 n 的, 这部分直接计算就可以,每一位可选的数字数量相乘即可,但是要注意减去开头是 0 的情况。另一部分是位数等于 n 的, 这里我们整体上还是按每一位可选数字数量来算, 但是要注意,如果前 m 位都跟 n[…m]的数字相等, 那当前位数字的可选范围就是从 0 到 n[m+1], 因为如果我们选择比 n[m+1]大的数字,那整体是肯定要>n 的,也就是超出范围了。同时我们还需要维护当前剩余的可选数字, 因为每个数字只能使用一次, 前面的位使用了,那当前位就不能再使用, 这一点我们通过 bit mask 来实现, 因为最多一共就 10 个可选的数字, 从 0 到 9



use std::collections::HashMap;

impl Solution {
   
    fn rc(
        digits: &[i32],
        pos: usize,
        is_equal: bool,
        choices: i32,
        cache: &mut HashMap<(usize, bool, i32), i32>,
    ) -> i32 {
   
        if pos == digits.len() {
   
            return 1;
        }
        let mut ans = 0;
        // 第一位的情况, 可选数字不能包括0
        if pos == 0 {
   
            for d in 1..=digits[pos] {
   
                if choices &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值