Skip to content

Commit ac9d1ad

Browse files
authored
Update count-numbers-with-unique-digits.cpp
1 parent 9bb11cd commit ac9d1ad

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

C++/count-numbers-with-unique-digits.cpp

+27-6
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,33 @@ class Solution {
77
if (n == 0) {
88
return 1;
99
}
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;
1514
}
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;
1738
}
1839
};

0 commit comments

Comments
 (0)