LeetCode 22. Generate Parentheses 括号生成(Java)

题目:

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:
[
"( ( ( ) ) ) ",
“( ( ) ( ) )”,
“( ( ) ) ( )”,
“( ) ( ( ) )”,
“( ) ( ) ( )”
]

解答:

在LeetCode 17 题中学习过回溯方法,这道题同理也采用了递归回溯的方法。即不断尝试增加“(”,若左括号剩余个数为0,不满足条件之后,再回溯返回,增加“)”。待获取目标值后,再退回一步继续递归选择其他排列。此为典型的回溯思想。

具体思路如下:

  1. 判断剩余左右括号数是否都为0,若left==0 && right==0,说明所有括号都排列完成,将此时的排列结果 str 放入 List 中。
  2. 若 left>0,说明还有剩余的左括号可参与排列,在当前序列 res 后增加 ‘(’,再递归
  3. 若 right > left,则说明还有右括号可参与排列,在当前序列 res 后增加 ‘)’,再递归。

注意,要使最终的组合序列为有效括号(即对于任意一个左括号,其右边一定有个右括号与之对应),例如 (()()), 从左边起,取到任意某位置得到的串,必须保证左括号数量 >= 右括号的数量。因此在递归过程中,剩余未添加的左括号个数 left 不能大于剩余右括号的个数 right。所以当退出递归时,如果剩余的右括号数量 right > 剩余的左括号数量 left,则将右括号加入输出串。 直到最后剩余的左括号和右括号都为0时,即可打印一个输出串

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        String str = "";
        generateParenthesis(res, str, n, n);
        return res;
    }
    private void generateParenthesis(List<String> res, String str, int left, int right) {
        if(left==0 && right==0) {
            res.add(str);
            return;
        }
        if(left > 0) {
            generateParenthesis(res, str+'(', left-1, right);
        }
        if(right > left) {
            generateParenthesis(res, str+')', left, right-1);
        }
    }
}

你可能感兴趣的:(LeetCode)