Generate Binary Strings Without Adjacent Zeros - Enumeration [JS]
Solution: Enumeration
Use enumeration to generate all strings of length n
, level by level from length 1
to length n
.
For each round,
- Keep track of the strings with length
i - 1
. - Go through every string with length
i - 1
and generate up to two new strings appending either0
or1
. - Note: We can only append
0
if the last character of the string is not0
, since there can't be two consecutive0s
.
Time Complexity: O(n * 2^n)
Space Complexity: O(2^n)
var validStrings = function(n) {
let prev = ["0", "1"];
for (let i = 2; i <= n; i++) {
let curr = [];
for (let prevStr of prev) {
if (prevStr[prevStr.length - 1] !== '0') {
curr.push(prevStr + '0');
}
curr.push(prevStr + '1');
}
prev = curr;
}
return prev;
};
Comments
Post a Comment