Generate Binary Strings Without Adjacent Zeros

MediumStringBacktrackingBit Manipulation

Solution

export function validStrings(n: number): string[] {
  const answer: string[] = [];
  function dfs(str: string) {
    if (str.length === n) {
      answer.push(str);
      return;
    }
    dfs(str + '1');
    if (str[str.length - 1] === '1') {
      dfs(str + '0');
    }
  }
 
  dfs('0');
  dfs('1');
  return answer;
}

Complexity

  • Time: O(2^N)
    • 0 또는 1N개의 길이 만큼의 combination을 구해야하기 때문에, O(2^N)이 된다.
  • Space: O(N)
    • 최대 recursionN번이기 때문에, call stack이 필요한 최대 크기는 O(N)이 된다.