-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotatedDigits.cpp
More file actions
29 lines (29 loc) · 954 Bytes
/
rotatedDigits.cpp
File metadata and controls
29 lines (29 loc) · 954 Bytes
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
class Solution {
public:
constexpr static int diffs[10] = {0, 0, 1, -1, -1, 1, 1, -1, 0, 1};
int rotatedDigits(int n) {
auto s = to_string(n);
int m = s.length();
vector<vector<int> > dp(m, vector<int>(2, -1));
function<int(int, bool, bool)> f;
f = [&](int i, bool has_diff, bool is_limit) -> int {
if (i == m) {
return has_diff;
}
if (!is_limit && dp[i][has_diff] >= 0) {
return dp[i][has_diff];
}
int res = 0, up = is_limit ? s[i] - '0' : 9;
for (int d = 0; d <= up; ++d) {
if (diffs[d] != -1) {// d is not 3/4/7
res += f(i + 1, has_diff || diffs[d], is_limit && d == up);
}
}
if (!is_limit) {
dp[i][has_diff] = res;
}
return res;
};
return f(0, false, true);
}
};