-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountSpecialNumbers.cpp
More file actions
44 lines (43 loc) · 1.33 KB
/
countSpecialNumbers.cpp
File metadata and controls
44 lines (43 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
static constexpr int fac[] = {
1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800
};
inline int A(int x, int y) {
return fac[x] / fac[x - y];
}
int countNumbersWithUniqueDigits(int n) {
int ret = 0;
for (int i = 0; i < n; ++i) {
ret += 9 * A(9, i);
}
return ret;
}
int countSpecialNumbers(int n) {
string n_str = to_string(n);
int m = n_str.size();
// 第一部分,m-1位的unique数字计算
int ret = countNumbersWithUniqueDigits(m - 1); // 不包含0
vector<bool> used(10, false);
// 第二部分,m位的整数,从高位开始计算
bool is_n_valid = true;
for (int i = 0; i < m; i++) {
char k = n_str[i] - '0';
int cnt = 0;
// 第0位不能为0
for (int j = (i == 0); j < k; j++) {
cnt += (!used[j]);
}
int A_ = A(10 - (i + 1), m - (i + 1));
ret += (cnt * A_);
if (used[k]) {
is_n_valid = false;
break;
}
used[k] = true;
}
ret += is_n_valid;
return ret;
}
};
// https://leetcode.cn/problems/count-special-integers/solution/pai-lie-zu-he-ji-suan-by-taiyuzhuo-2i4z/