- 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
- 48 lines of C++ from the credited upstream file 2801.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 countSteppingNumbers(string low, string high) {4 const string lowWithLeadingZeros =5 string(high.length() - low.length(), '0') + low;6 vector<vector<vector<vector<int>>>> mem(7 high.length(), vector<vector<vector<int>>>(8 11, vector<vector<int>>(2, vector<int>(2, -1))));9 return count(lowWithLeadingZeros, high, 0, 10, true, true,10 true, mem);11 }12 13 private:14 static constexpr int kMod = 1'000'000'007;15 16 17 18 19 20 int count(const string& low, const string& high, int i, int prevDigit,21 bool isLeadingZero, bool tight1, bool tight2,22 vector<vector<vector<vector<int>>>>& mem) {23 if (i == high.length())24 return 1;25 if (mem[i][prevDigit][tight1][tight2] != -1)26 return mem[i][prevDigit][tight1][tight2];27 28 int res = 0;29 const int minDigit = tight1 ? low[i] - '0' : 0;30 const int maxDigit = tight2 ? high[i] - '0' : 9;31 32 for (int d = minDigit; d <= maxDigit; ++d) {33 const bool nextTight1 = tight1 && (d == minDigit);34 const bool nextTight2 = tight2 && (d == maxDigit);35 if (isLeadingZero)36 37 res += count(low, high, i + 1, d, isLeadingZero && d == 0, nextTight1,38 nextTight2, mem);39 else if (abs(d - prevDigit) == 1)40 41 res += count(low, high, i + 1, d, false, nextTight1, nextTight2, mem);42 res %= kMod;43 }44 45 return mem[i][prevDigit][tight1][tight2] = res;46 }47};48