Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- vector<vector<int>> dp;
- vector<int> digits;
- int dcnt;
- int search(int pos, int limit, int lz, int state) {
- // printf("in search pos:%d limit:%d lz:%d state:%d\n", pos, limit, lz, state);
- if (pos == -1) return 1;
- int ub = limit ? digits[pos] : 9;
- int ret = 0;
- if (lz == 0 && limit == 0 && dp[pos][state] != 0) return dp[pos][state];
- for (int i = 0; i <= ub; ++i) {
- if (i == 0 && lz == 1)
- ret += search(pos - 1, 0, lz, state);
- if (((1 << i) & state) == 0) {
- if (i == 0) {
- if (lz == 0)
- ret += search(pos - 1, 0, 0, state | 1);
- } else {
- ret += search(pos - 1, limit && i == ub, 0, state | (1 << i));
- }
- }
- }
- if (lz == 0 && limit == 0) dp[pos][state] = ret;
- return ret;
- }
- public:
- int countSpecialNumbers(int n) {
- dp = vector<vector<int>>(1<<4, vector<int>(1 << 10));
- for (int i = 1; i <= 9; ++i) {
- dp[0][1 << i] = 1;
- }
- int nn = n;
- dcnt = 0;
- digits = vector<int>(16);
- while(nn != 0) { digits[dcnt++] = nn % 10; nn /= 10; }
- int ans = search(dcnt - 1, 1, 0, 0);
- // ans += search(dcnt - 1, 0, 1, 0);
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement