- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of C++ from the credited upstream file 2827.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int numberOfBeautifulIntegers(int low, int high, int k) {4 const string lowString = to_string(low);5 const string highString = to_string(high);6 const string lowWithLeadingZeros =7 string(highString.length() - lowString.length(), '0') + lowString;8 vector<vector<vector<vector<vector<vector<int>>>>>> mem(9 highString.length(),10 vector<vector<vector<vector<vector<int>>>>>(11 10, vector<vector<vector<vector<int>>>>(12 10, vector<vector<vector<int>>>(13 k, vector<vector<int>>(2, vector<int>(2, -1))))));14 return count(lowWithLeadingZeros, highString, k, 0, 0, 0, 0, true, true,15 true, mem);16 }17 18 private:19 20 21 22 23 24 int count(const string& low, const string& high, int k, int i, int even,25 int odd, int remainder, bool isLeadingZero, bool tight1,26 bool tight2,27 vector<vector<vector<vector<vector<vector<int>>>>>>& mem) {28 if (i == high.length())29 return !isLeadingZero && even == odd && remainder == 0;30 if (mem[i][even][odd][remainder][tight1][tight2] != -1)31 return mem[i][even][odd][remainder][tight1][tight2];32 33 int res = 0;34 const int minDigit = tight1 ? low[i] - '0' : 0;35 const int maxDigit = tight2 ? high[i] - '0' : 9;36 37 for (int d = minDigit; d <= maxDigit; ++d) {38 const int nextEven = even + ((!isLeadingZero || d > 0) && d % 2 == 0);39 const int nextOdd = odd + (d % 2 == 1);40 const int nextRemainder = (remainder * 10 + d) % k;41 const bool nextTight1 = tight1 && (d == minDigit);42 const bool nextTight2 = tight2 && (d == maxDigit);43 res += count(low, high, k, i + 1, nextEven, nextOdd, nextRemainder,44 isLeadingZero && d == 0, nextTight1, nextTight2, mem);45 }46 47 return mem[i][even][odd][remainder][tight1][tight2] = res;48 }49};50