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
|
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int k;
int dp(int pos, int even, int odd, int mod, bool tight, const vector<int>& digits, vector<vector<vector<vector<vector<int>>>>>& memo) {
if (pos == digits.size()) return even == odd && mod == 0;
if (memo[pos][even][odd][mod][tight] != -1) return memo[pos][even][odd][mod][tight];
int res = 0, up = tight ? digits[pos] : 9;
for (int d = 0; d <= up; ++d) {
int ne = even + (d%2==0);
int no = odd + (d%2==1);
res += dp(pos+1, ne, no, (mod*10+d)%k, tight && d==up, digits, memo);
}
return memo[pos][even][odd][mod][tight] = res;
}
int f(int x) {
vector<int> digits;
for (; x; x/=10) digits.push_back(x%10);
reverse(digits.begin(), digits.end());
int n = digits.size();
vector<vector<vector<vector<vector<int>>>>> memo(n+1, vector<vector<vector<vector<int>>>>(n+1, vector<vector<vector<int>>>(n+1, vector<vector<int>>(k, vector<int>(2, -1)))));
return dp(0,0,0,0,1,digits,memo);
}
int numberOfBeautifulIntegers(int low, int high, int K) {
k = K;
return f(high) - f(low-1);
}
};
|