Advertisement
pb_jiang

lc t4

Aug 13th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. class Solution {
  2.     vector<vector<int>> dp;
  3.     vector<int> digits;
  4.     int dcnt;
  5.    
  6.     int search(int pos, int limit, int lz, int state) {
  7.         // printf("in search pos:%d limit:%d lz:%d state:%d\n", pos, limit, lz, state);
  8.         if (pos == -1) return state < 1 ? 0 : 1;
  9.         int ub = limit ? digits[pos] : 9;
  10.         int ret = 0;
  11.         if (lz == 0 && limit == 0 && dp[pos][state] != -1) return dp[pos][state];
  12.  
  13.         if (lz == 1) ret += search(pos - 1, 0, lz, state);
  14.         for (int i = 0; i <= ub; ++i) {
  15.             if (((1 << i) & state) == 0) {            
  16.                 if (i == 0) {
  17.                     if (lz == 0)
  18.                         ret += search(pos - 1, 0, 0, state | 1);
  19.                 } else {
  20.                     ret += search(pos - 1, limit && i == ub, 0, state | (1 << i));
  21.                 }
  22.             }
  23.         }
  24.        
  25.         if (lz == 0 && limit == 0) dp[pos][state] = ret;
  26.         return ret;
  27.     }
  28. public:
  29.     int countSpecialNumbers(int n) {
  30.         dp = vector<vector<int>>(1<<4, vector<int>(1 << 10, -1));
  31.         int nn = n;
  32.         dcnt = 0;
  33.         digits = vector<int>(16);
  34.         while(nn != 0) { digits[dcnt++] = nn % 10; nn /= 10; }
  35.         int ans = search(dcnt - 1, 1, 1, 0);
  36.         return ans;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement