22 Generate Parentheses

https://leetcode.com/problems/generate-parentheses/#/description

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

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

分析及代码

基础的backtracking

public List<String> generateParenthesis(int n) {
    List<String> res = new ArrayList<>();
    if(n <= 0) {
        return res;
    }
    generator(res, "", n, n);
    return res;
}

private void generator(List<String> res, String cur, int leftLeft, int rightLeft) {
    if(leftLeft > rightLeft || leftLeft < 0 || rightLeft < 0) {
        return;
    }
    if(leftLeft == 0 && rightLeft == 0) {
        res.add(cur);
        return;
    }
    generator(res, cur + "(", leftLeft - 1, rightLeft);
    generator(res, cur + ")", leftLeft, rightLeft - 1);
}

O(2^n)

一棵剪枝过的二叉树

results matching ""

    No results matching ""