File tree Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change @@ -38,6 +38,7 @@ mod a0937_reorder_data_in_log_files;
3838mod a0949_largest_time_for_given_digits;
3939mod a0973_k_closest_points_to_origin;
4040mod a0980_unique_paths_iii;
41+ mod a1012_numbers_with_repeated_digits;
4142mod a1018_binary_prefix_divisible_by_5;
4243mod a1021_remove_outermost_parentheses;
4344mod a1047_remove_all_adjacent_duplicates_in_string;
You can’t perform that action at this time.
0 commit comments