forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
34 lines (34 loc) · 1.04 KB
/
Solution.cpp
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
class Solution {
public:
int countSpecialNumbers(int n) {
string s = to_string(n);
int m = s.size();
int f[m][1 << 10];
memset(f, -1, sizeof(f));
auto dfs = [&](auto&& dfs, int i, int mask, bool lead, bool limit) -> int {
if (i >= m) {
return lead ^ 1;
}
if (!limit && !lead && f[i][mask] != -1) {
return f[i][mask];
}
int up = limit ? s[i] - '0' : 9;
int ans = 0;
for (int j = 0; j <= up; ++j) {
if (mask >> j & 1) {
continue;
}
if (lead && j == 0) {
ans += dfs(dfs, i + 1, mask, true, limit && j == up);
} else {
ans += dfs(dfs, i + 1, mask | (1 << j), false, limit && j == up);
}
}
if (!limit && !lead) {
f[i][mask] = ans;
}
return ans;
};
return dfs(dfs, 0, 0, true, true);
}
};