<AI/>
enru
Все статьи

Generate parentheses

LeetCode 22: Generate all valid parentheses sequences of n pairs, from brute force to backtracking with counters.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#string#backtracking
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that generates all possible valid parentheses sequences of length 2n.

Input: a number: the number of pairs of parentheses.

Output: an array of strings: all possible valid parentheses sequences of length 2n.

Constraints

  • 1 <= n <= 8

Examples

Input: 3

Answer: ["((()))", "(()())", "(())()", "()(())", "()()()"]

Brute force approach

Let's split the problem into 2 subproblems:

  • generate all possible strings of length 2n consisting of ( and );
  • check which of them are valid parentheses sequences.

Generating all strings of length 2n made of "(" and ")"

This is quite straightforward:

  • Create the initial array. In our case it has one element, since a valid parentheses sequence can only start with an opening bracket.
  • Run a loop up to 2 * n, where n is the number of pairs.
  • On each iteration, go over all elements of the previous result and add 2 new variants: one with an opening bracket and one with a closing bracket.
typescript
function generateAllPossibleParenthesis(n: number): string[] {
  let combinations: string[] = ['('];
 
  for (let i = 1; i < n * 2; i++) {
    const newArray: string[] = [];
 
    combinations.forEach((item) => {
      newArray.push(item + '(');
      newArray.push(item + ')');
    });
 
    combinations = newArray;
  }
 
  return combinations;
}

Checking whether a string is a valid parentheses sequence

We've already covered this problem. To avoid repeating ourselves, we'll reuse the ready-made solution for validating a parentheses sequence.

Putting it all together, we get the following solution.

typescript
export function generateParenthesisBruteforce(n: number): string[] {
  const combinations = generateAllPossibleParenthesis(n);
  let res: string[] = [];
 
  combinations.forEach((parenthesis) => {
    if (isValid(parenthesis)) {
      res.push(parenthesis);
    }
  });
 
  return res;
}
 
function generateAllPossibleParenthesis(n: number): string[] {
  let combinations: string[] = ['('];
 
  for (let i = 1; i < n * 2; i++) {
    const newArray: string[] = [];
 
    combinations.forEach((item) => {
      newArray.push(item + '(');
      newArray.push(item + ')');
    });
 
    combinations = newArray;
  }
 
  return combinations;
}
 
export const isValid = (brackets: string): boolean => {
  const stack: string[] = [];
 
  const closeBrackets: Record<string, string> = {
    ')': '(',
    ']': '[',
    '}': '{',
  };
 
  for (let i = 0; i < brackets.length; i++) {
    const char = brackets[i];
    const openBracket = closeBrackets[char];
 
    if (openBracket) {
      if (stack.length === 0) {
        return false;
      }
 
      const lastOpenBracket = stack[stack.length - 1];
 
      if (lastOpenBracket !== openBracket) {
        return false;
      }
 
      stack.pop();
    } else {
      stack.push(char);
    }
  }
 
  return stack.length === 0;
};

Complexity Analysis

Time Complexity

The optimal complexity of validating a string is O(n). In our case all strings have length 2n, but the complexity is still O(n).

Now let's estimate the number of generated strings. Every character except the first is an arbitrary symbol from the set ["(", ")"], and the resulting string has 2 * n characters. So the number of strings is 22n-1.

The overall complexity can be estimated as O(n * 22n).

Space Complexity

The biggest memory cost here is storing all possible strings. We need an array of 22n-1 strings, each of length 2 * n. So we're talking about O(n * 22n) additional memory.

In combinatorics problems, a brute force solution that enumerates all possible variants is usually far from optimal, since its complexity grows very quickly with the input size. In this problem, for n = 8 the number of all possible strings is already 32768 (215).

Optimized brute force

The main problem of the brute force solution is that it generates lots of strings that are obviously invalid. We can fix this by adding checks before appending each character that discard obviously invalid options.

The problem is greatly simplified by the fact that there's only one type of bracket: round ones. In this case a simple counter is enough to validate a sequence. Let's describe when we can add each kind of bracket:

  • We can add an opening bracket if the total number of opening brackets in the string doesn't exceed n.
  • We can add a closing bracket if the number of opening brackets in the string is greater than the number of closing ones.

With this approach we don't need to validate the resulting strings afterwards, so we can drop one of the factors in our complexity estimate.

typescript
export const generate = (n: number, row: string, opened: number, closed: number, answer: string[]): void => {
  if (row.length === n * 2) {
    answer.push(row);
    return;
  }
 
  if (opened >= closed && opened < n) {
    generate(n, row + '(', opened + 1, closed, answer);
  }
 
  if (opened > closed) {
    generate(n, row + ')', opened, closed + 1, answer);
  }
};
 
export const generateParenthesis = (n: number): string[] => {
  const res: string[] = [];
  generate(n, '(', 1, 0, res);
  return res;
};

Complexity Analysis

Time Complexity

This solution doesn't need to validate sequences. We replaced validation with checking whether an opening or closing bracket can be added while generating the string. Moreover, since we keep counters of the total number of opening brackets and of unclosed brackets, this check takes constant time.

The number of generated strings is at most 22n-1.

In reality there are far fewer strings, since we discard all invalid sequences early. But estimating their exact number is much harder. It's fair to say that the worst-case complexity is O(22n-1).

Space Complexity

We need memory to store all resulting strings. Each string has length 2 * n. As with time complexity, it's fair to say that the number of strings is comparable to 22n-1.

So the space complexity is O(n * 22n-1).