括号生成

LeetCode-generateParenthese

Posted by Sike on October 2, 2020

题目描述

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。

例如,给出n=3,解集为:

"((()))", "(()())", "(())()", "()()()", "()(())"

示例1

输入

1

输出

["()"]

示例2

输入

2

输出

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

思路

回溯法

左子树表示添加左括号

右子树表示添加右括号

条件:

左括号个数必须大于右括号个数

parentheses

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;

public class Solution {
    /**
     *
     * @param n int整型
     * @return string字符串ArrayList
     */
    public ArrayList<String> generateParenthesis (int n) {
        // write code here
        ArrayList<String> res = new ArrayList<String>();

        dfs(res, "", n, 0, 0);

        return res;

    }
    private void dfs(ArrayList<String> res, String path, int n, int lc, int rc){
        if(lc > n || rc > n || rc > lc)
            return;
        else if(lc == n && rc == n){
            res.add(path);
            return;
        }
        else{
            dfs(res, path + "(", n, lc + 1, rc);
            dfs(res, path + ")", n, lc, rc + 1);
        }
    }
}