leetcode-22

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution22t {
    public static List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
        backtrack(ans, "", 0, 0, n);
        return ans;
    }

    public static void backtrack(List<String> ans, String cur, int open, int close, int max){
        if (cur.length() == max * 2) {
            ans.add(cur);
            return;
        }

        if (open < max)
            backtrack(ans, cur+"(", open+1, close, max);
        if (close < open)
            backtrack(ans, cur+")", open, close+1, max);
    }

    public static void main(String[] args) {
        generateParenthesis(3);
    }
}

这道题的关键在于当open == max的时候,此时cur为((( 

然后顺序到下面的close < open,第一个ans结果为((())),此时cur.length == max * 2,

此时需要弹栈到 open == 2了,此时cur为((,顺序到close < open的判断,close此时为0,open为2,然后这层循环后cur为(()

...结束

这道题的关键还是考察递归和回溯的思想,递归就要理解栈的意思,无非是你的每次操作包括变量值都压栈,再弹出。

猜你喜欢

转载自www.cnblogs.com/CherryTab/p/12107621.html