[LeetCode] Non-negative Integers without Consecutive Ones

600. Non-negative Integers without Consecutive Ones

Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int dfs(vector<int>& prefixSum, int num) {
if(num <= 1) return num ? 2 : 1;
for(int i = 31; i >= 0; i--) {
if(num & (1<<i)) {
return prefixSum[i-1] + (num & 1<<(i-1) ? dfs(prefixSum, (1<<(i-1))-1) : dfs(prefixSum, (num ^ (1<<i))));
}
}
return -1;
}
public:
int findIntegers(int n) {
if(n <= 1) return n ? 2 : 1;
vector<int> dp{2, 1}, prefixSum{2,3};
for(int i = 2; i < 31; i++) {
dp.push_back(prefixSum[i-2]);
prefixSum.push_back(prefixSum.back() + dp.back());
}

return dfs(prefixSum, n);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/non-negative-integers-without-consecutive-ones/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.