Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 73cc484

Browse files
author
guangsheng.li01
committed
Solved 1012
1 parent 23d77ca commit 73cc484

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* [1012] numbers-with-repeated-digits
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
impl Solution {
10+
pub fn num_dup_digits_at_most_n(n: i32) -> i32 {
11+
n - Self::digit_dp(n)
12+
}
13+
14+
fn digit_dp(n: i32) -> i32 {
15+
let mut n = n;
16+
let mut digits = Vec::new();
17+
while n > 0 {
18+
digits.push(n % 10);
19+
n /= 10;
20+
}
21+
let k = digits.len();
22+
23+
let mut used: [i32; 10] = [0; 10];
24+
let mut total = 0;
25+
26+
for i in 1..k {
27+
total += 9 * Self::a(9, i as i32 - 1);
28+
}
29+
30+
for i in 0..k {
31+
let i = k - 1 - i;
32+
let num = digits[i];
33+
34+
for j in (if i == k - 1 { 1 } else { 0 })..num {
35+
if used[j as usize] != 0 {
36+
continue;
37+
}
38+
total += Self::a((10 - k + i) as i32, i as i32);
39+
}
40+
41+
used[num as usize] += 1;
42+
if used[num as usize] > 1 {
43+
break;
44+
}
45+
46+
if i == 0 {
47+
total += 1;
48+
}
49+
}
50+
51+
total
52+
}
53+
54+
fn a(a: i32, b: i32) -> i32 {
55+
Self::fact(a) / Self::fact(a - b)
56+
}
57+
58+
fn fact(n: i32) -> i32 {
59+
if n == 0 || n == 1 {
60+
return 1;
61+
}
62+
return n * Self::fact(n - 1);
63+
}
64+
}
65+
// solution impl ends here
66+
67+
// solution tests starts here
68+
69+
#[cfg(test)]
70+
mod tests {
71+
use super::*;
72+
73+
#[test]
74+
fn test_case0() {
75+
assert_eq!(Solution::num_dup_digits_at_most_n(20), 1);
76+
assert_eq!(Solution::num_dup_digits_at_most_n(100), 10);
77+
assert_eq!(Solution::num_dup_digits_at_most_n(1000), 262);
78+
}
79+
}
80+
81+
// solution tests ends here

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ mod a0937_reorder_data_in_log_files;
3838
mod a0949_largest_time_for_given_digits;
3939
mod a0973_k_closest_points_to_origin;
4040
mod a0980_unique_paths_iii;
41+
mod a1012_numbers_with_repeated_digits;
4142
mod a1018_binary_prefix_divisible_by_5;
4243
mod a1021_remove_outermost_parentheses;
4344
mod a1047_remove_all_adjacent_duplicates_in_string;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /