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 & (1 <<

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

被折叠的 条评论
为什么被折叠?



