【LeetCode】22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]


Solution:

This problem can be solved by backtracking.

F(n, m) means we need n "(" and m ")"

Recursive definition: F(n, m) = ["(" + F(n - 1, m)] + [")" + F(n, m - 1)]

Assuming n == m == k(given number) at first, during the backtracking process, when n > m, which means we need "(" more than ")" , that is to say, we have redundant ")" in the front of string, this is invalid no matter how we make F(n, m), so return null.

Here is a example of F(2, 2)

F (2, 2) = ["(" + F(1, 2)] + [")" + F(2, 1)]  note: the right [] should return null since we have extra ")" in the front and we can never make it work for the right []

F(1, 2) = ["(" + F(0, 2)] + [")" + F(1, 1)]

F(0, 2) = "))"

F(1, 1) = ["(" + F(0, 1)] + [")" + F(1, 0)]   note: the right [] should return null

Then we backtrack until we return the result of F(2, 2).


Code 1

public List generateParenthesis(int n) {
        List res = new ArrayList<>();
        backtrack(n, n, "", res);
        return res;
    }
    
    private void backtrack(int left, int right, String s, List res) {
        if (left > right) {
            return;
        }
        if (left == 0 && right == 0) {
            res.add(s);
            return;
        }
        if (left > 0) {
            backtrack(left - 1, right, s + "(", res);
        }
        if (right > 0) {
            backtrack(left, right - 1, s + ")", res);
        }
    }
Code 2: Same Idea
public List generateParenthesis(int n) {
        List res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        
        if (n == 0) {
            return res;
        }
        recursive(0, 0, n, res, sb);
        return res;
    }
    
    private void recursive(int left, int right, int n, List res, StringBuilder sb) {
        if (left < right) {
            return;
        }
        if (left == n && right == n) {
            res.add(sb.toString());
            return;
        }
        if (left < n) {
            StringBuilder newStr = new StringBuilder(sb.toString());
            newStr.append("(");
            recursive(left + 1, right, n, res, newStr);
        }
        if (right < n) {
            StringBuilder newStr = new StringBuilder(sb.toString());
            newStr.append(")");
            recursive(left, right + 1, n, res, newStr);
        }
    }


你可能感兴趣的:(LeetCode)