File tree 1 file changed +27
-6
lines changed
1 file changed +27
-6
lines changed Original file line number Diff line number Diff line change @@ -7,12 +7,33 @@ class Solution {
7
7
if (n == 0 ) {
8
8
return 1 ;
9
9
}
10
- int count = 10 ; // f(1) = 10
11
- for (int k = 2 , fk = 9 ; k <= n; ++k) {
12
- // f(k) = f(k - 1) * (10 - (k - 1))
13
- fk *= 10 - (k - 1 );
14
- count += fk;
10
+ int result = 1 ;
11
+ for (int i = 0 , cnt = 1 ; i < n - 1 ; ++i) {
12
+ cnt *= 9 - i;
13
+ result += cnt;
15
14
}
16
- return count; // sum(f(k), k=1~n)
15
+ return 1 + 9 * result;
16
+ }
17
+ };
18
+
19
+ // Time: O(n)
20
+ // Space: O(n)
21
+ class Solution2 {
22
+ public:
23
+ int countNumbersWithUniqueDigits (int n) {
24
+ vector<int > fact (2 , 1 );
25
+ const auto & nPr = [&](int n, int k) {
26
+ while (size (fact) <= n) { // lazy initialization
27
+ fact.emplace_back (fact.back () * size (fact));
28
+ }
29
+ return fact[n] / fact[n - k];
30
+ };
31
+
32
+ int result = 0 ;
33
+ for (int i = 0 ; i < n; ++i) {
34
+ result += nPr (9 , i);
35
+ }
36
+ result *= 9 ;
37
+ return ++result;
17
38
}
18
39
};
You can’t perform that action at this time.
0 commit comments