| 12
 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
 
 | class Solution {public:
 int d;
 string lowStr, highStr;
 vector<vector<int>> dp;
 
 int digitsCount(int d, int low, int high) {
 this->d = d;
 highStr = to_string(high);
 lowStr = to_string(low);
 int n = highStr.size();
 dp.resize(n, vector<int>(n, -1));
 lowStr = string(n - lowStr.size(), '0') + lowStr;
 int res = dfs(0, 0, true, true, false);
 return res;
 }
 
 int dfs(int index, int count, bool limit_low, bool limit_high, bool is_num) {
 if (index == highStr.size()) {
 return is_num ? count : 0;
 }
 
 if (!limit_low && !limit_high && is_num && dp[index][count] != -1) {
 return dp[index][count];
 }
 
 int res = 0;
 if (!is_num && lowStr[index] -'0' == 0)
 res += dfs(index + 1, count, true, false, false);
 
 int lo = limit_low ? lowStr[index] - '0' : 0;
 int hi = limit_high ? highStr[index] - '0' : 9;
 for (int i = max(lo, 1 - is_num); i <= hi; i++) {
 res += dfs(index + 1, count + (i == d), limit_low && i == lo, limit_high && i == hi, true);
 }
 if (!limit_low && !limit_high && is_num) {
 dp[index][count] = res;
 }
 return res;
 }
 };
 
 |