- 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
- 40 lines of C++ from the credited upstream file 2376.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 4 int countSpecialNumbers(int n) {5 const int digitSize = log10(n) + 1;6 vector<vector<vector<int>>> mem(7 digitSize + 1, vector<vector<int>>(1 << 10, vector<int>(2, -1)));8 return count(to_string(n), 0, 0, true, mem) - 1; 9 }10 11 private:12 13 14 15 int count(const string& s, int i, int used, bool tight,16 vector<vector<vector<int>>>& mem) {17 if (i == s.length())18 return 1;19 if (mem[i][used][tight] != -1)20 return mem[i][used][tight];21 22 int res = 0;23 const int maxDigit = tight ? s[i] - '0' : 9;24 25 for (int d = 0; d <= maxDigit; ++d) {26 27 if (used >> d & 1)28 continue;29 30 const bool nextTight = tight && (d == maxDigit);31 if (used == 0 && d == 0) 32 res += count(s, i + 1, used, nextTight, mem);33 else34 res += count(s, i + 1, used | 1 << d, nextTight, mem);35 }36 37 return mem[i][used][tight] = res;38 }39};40