forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
84 lines (67 loc) · 2.11 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/// Source : https://leetcode.com/problems/rotated-digits/description/
/// Author : liuyubobobo
/// Time : 2018-03-05
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Memory Search
/// Same algorithm to Leetcode 788
///
/// dp[i][eq][last_one] means we search first i digits,
/// and the i-th digit is equal (or not) to the i-th digit in N (binary form)
/// and last digit of the search is last_one(true or false)
///
/// Time Complexity: O(logN)
/// Space Complexity: O(logN)
class Solution {
private:
vector<vector<vector<int>>> memo;
public:
int findIntegers(int num) {
if(num == 0)
return 1;
string binary = to_binary(num);
// cout << binary << endl;
memo = vector<vector<vector<int>>>(binary.size(), vector<vector<int>>(2, vector<int>(2, -1)));
assert(binary[0] == '1');
return search(0, true, false, binary);
}
private:
int search(int index, bool eq, bool last_one, const string& binary){
if(index == binary.size())
return 1;
if(memo[index][eq][last_one] != -1)
return memo[index][eq][last_one];
int res = 0;
char bound = (eq ? binary[index] : '1');
for(char c = '0' ; c <= bound ; c ++){
if(last_one && c == '1')
continue;
bool this_one = (c == '1');
if(eq && c == bound)
res += search(index + 1, true, this_one, binary);
else
res += search(index + 1, false, this_one, binary);
}
return memo[index][eq][last_one] = res;
}
string to_binary(int num){
string res = "";
while(num){
res += ('0' + num%2);
num /= 2;
}
reverse(res.begin(), res.end());
return res;
}
};
int main() {
cout << Solution().findIntegers(0) << endl;
cout << Solution().findIntegers(1) << endl;
cout << Solution().findIntegers(2) << endl;
cout << Solution().findIntegers(3) << endl;
cout << Solution().findIntegers(4) << endl;
cout << Solution().findIntegers(5) << endl;
return 0;
}