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 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { public: inline int c2i(const char &c) { return c - '0'; }
long long dfs(const int &n, const string &start_str, const string &finish_str, int i, bool limit_high, bool limit_low, int &post_fix_index, const int &limit_num, const string &s, vector<vector<long long>> &memo) { if (i == n) { return 1; }
if (!limit_high && !limit_low && memo[i][0] != -1) { return memo[i][0]; } // 限制一个数位的最高和最低的值 int high_num = limit_high ? c2i(finish_str[i]) : 9; int low_num = limit_low ? c2i(start_str[i]) : 0;
long long result = 0; if (i < post_fix_index) { for (int new_num = low_num; new_num <= min(high_num,limit_num); new_num++) { result += dfs(n, start_str, finish_str, i+1, limit_high && new_num==high_num, limit_low && new_num == low_num, post_fix_index, limit_num, s, memo); } } else { int x = c2i(s[i - post_fix_index]); if (x >= low_num && x <= min(high_num,limit_num)) { result = dfs(n, start_str, finish_str, i+1, limit_high && x==high_num, limit_low && x == low_num, post_fix_index, limit_num, s, memo); } }
if (!limit_high && !limit_low) { memo[i][0] = result; }
return result; }
long long numberOfPowerfulInt(long long start, long long finish, int limit, string s) { string finish_str = to_string(finish); string start_str = to_string(start);
int n = finish_str.length();
start_str = string(n - start_str.length(), '0') + start_str;
int post_index = n - s.size(); // cout << "post:" << post_index << endl;
vector<vector<long long>> memo(n, vector<long long>(1, -1));
long long res = dfs(n, start_str, finish_str, 0, true, true, post_index, limit, s, memo);
return res; } };
|