-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcount-beautiful-numbers.cpp
41 lines (39 loc) · 1.41 KB
/
count-beautiful-numbers.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
35
36
37
38
39
40
41
// Time: O(logr * 2 * 10 * s)
// Space: O(s) ~= O(2026), s = len(states)
// dp
class Solution {
public:
int beautifulNumbers(int l, int r) {
const auto& count = [](int x) {
const auto& s = to_string(x);
vector<unordered_map<int, unordered_map<int, int>>> dp(2);
dp[1][1][0] = 1;
for (int i = 0; i < size(s); ++i) {
vector<unordered_map<int, unordered_map<int, int>>> new_dp(2);
const int c = s[i] - '0';
for (int b = 0; b < 2; ++b) {
for (const auto& [mul, kvp] : dp[b]) {
for (const auto& [total, cnt] : kvp) {
for (int x = 0; x <= (!b ? 9 : c); ++x) {
new_dp[b && x == c][total == 0 && x == 0 ? mul : (mul * x)][total + x] += cnt;
}
}
}
}
swap(dp, new_dp);
}
int result = 0;
for (int b = 0; b < 2; ++b) {
for (const auto& [mul, kvp] : dp[b]) {
for (const auto& [total, cnt] : kvp) {
if (total && mul % total == 0) {
result += cnt;
}
}
}
}
return result;
};
return count(r) - count(l - 1);
}
};