
Sponsored
Sponsored
This approach utilizes dynamic programming to count the number of non-negative integers without consecutive ones. By breaking down the problem, we can avoid redundant work by storing solutions to subproblems.
Time Complexity: O(1) since we iterate over a fixed number of bits (30 bits for int).
Space Complexity: O(1) for storing a constant size dp array.
1function findIntegers(num) {
2 let dp = Array(31).fill(0);
3 dp[0] = 1;
4 dp[1] = 2;
5 for (let i = 2; i < 31; i++) {
6 dp[i] = dp[i - 1] + dp[i - 2];
7 }
8
9 let prev_bit = 0, result = 0;
10
11 for (let i = 29; i >= 0; i--) {
12 if ((num & (1 << i)) !== 0) {
13 result += dp[i];
14 if (prev_bit === 1) {
15 return result;
16 }
17 prev_bit = 1;
18 } else {
19 prev_bit = 0;
20 }
21 }
22 return result + 1;
23}
24
25const n = 5;
26console.log(findIntegers(n));JavaScript employs an array-based approach akin to other languages. The dp structure helps in precomputing and checking valid combinations of non-consecutive ones, effectively counting suitable numbers. Each bit of num is considered individually.
In this approach, we tackle the problem recursively and use memoization to store and retrieve solutions to subproblems, thereby optimizing overlapping subproblem calculations.
Time Complexity: Generally O(log n), as the recursion iterates over each bit once.
Space Complexity: O(log n) due to the recursive call stack and memo storage.
1class Solution:
2 def __init__(self)
The Python solution mirrors the C++ solution by breaking down the integer into binary bits and evaluating recursively through depth-first search. It stores computed results in a dictionary to avoid re-calculating overlapping subproblems.