Generate Parentheses 生成括号 LeetCode 22

问题

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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

分析

递归的思想


if (左右括号都已用完) {
  加入解集,返回
}
//否则开始试各种选择
if (还有左括号可以用) {
  加一个左括号,继续递归
}
if (右括号小于左括号) {
  加一个右括号,继续递归
}

代码

 public static List<String> generateParentheses(int n){
        List<String> result = new ArrayList<>();
        dfs(0, 0, "", result, n);
        return result;

    }

    public static void dfs(int left, int right, String out, List<String> result, int n){
        if(left == n && right == n){
            result.add(out);
            return;
        }
        if(left < n){
            dfs(left + 1, right, out + "(", result, n);
        }
        if(right < left){
            dfs(left, right + 1, out + ")", result, n);
        }
    }

public static void main(String[] args) {
        System.out.println(generateParentheses(3).toString());

    }

结果

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

参考

22. Generate Parentheses

你可能感兴趣的:(Data,structure,生成括号,LeetCode)