We call a positive integer special if all of its digits are distinct.
Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Example 1:
Input: n = 20
Output: 19
Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
Example 2:
Input: n = 5
Output: 5
Explanation: All the integers from 1 to 5 are special.
Example 3:
Input: n = 135
Output: 110
Explanation: There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.
Constraints:
- 1 <= n <= 2 * 109
最终答案分两部分:
- 位数小于 n 的位数的数字, 这部分取值不需要考虑>n 的情况, 因为位数比 n 的位数少, 所以这部分数字一定是< n 的
- 位数等于 n 的位数的数字, 这部分要考虑>n 的情况, 从左向右按位遍历, 当前一位的数字与对应的 n 的数字相等时,当前位就不能超过对应的 n 的数字, 比如 n = 23, 当我们考虑第一位为 1 的时候, 第二位可以取除 1 外的任何数, 当第一位为 2 的时候, 那第二位就只能考虑<=3 的数字, 此时因为 2 已经被第一位占用了, 所以可选的只有 0、1 和 3。
已经使用的数字我们用一个 mask 来保存, 每次取值只能取没有用过的数字。
最后要注意的是 0 不能在第一位
impl Solution {
fn full(num_of_digits: i32, is_first: bool, mask: i32) -> i32 {
if num_of_digits == 0 {
return 0;
}
let mut ans = 0;
if num_of_digits == 1 {
for i in if is_first { 1 } else { 0 }..10 {
if (1 << i) & mask == 0 {
ans += 1;
}
}
return ans;
}
for i in if is_first { 1 } else { 0 }..10 {
if (1 << i) & mask == 0 {
ans += Solution::full(num_of_digits - 1, false, mask | (1 << i));
}
}
ans
}
fn rc(digits: &Vec<i32>, i: usize, has_reach_top: bool, mask: i32) -> i32 {
if i == digits.len() {
return 1;
}
let mut ans = 0;
if has_reach_top {
for j in 0..10 {
if j <= digits[i] && (mask & (1 << j as usize)) == 0 {
let next_mask = mask | (1 << j as usize);
ans += Solution::rc(digits, i + 1, digits[i] == j, next_mask);
}
}
} else {
for j in 0..10 {
if (mask & (1 << j as usize)) == 0 {
let next_mask = mask | (1 << j as usize);
ans += Solution::rc(digits, i + 1, false, next_mask);
}
}
}
ans
}
pub fn count_special_numbers(mut n: i32) -> i32 {
let mut digits = Vec::new();
while n > 0 {
digits.push(n % 10);
n /= 10;
}
digits.reverse();
let mut ans = 0;
for i in 1..digits.len() {
ans += Solution::full(i as i32, true, 0);
}
for i in 1..10 {
if i <= digits[0] {
ans += Solution::rc(&digits, 1, i == digits[0], 1 << i as usize);
}
}
ans
}
}