力扣 22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        StringBuilder path = new StringBuilder();
        backtrack(res, path, 0, 0, n);
        return res;
    }

    private void backtrack(List<String> res, StringBuilder path, int open, int close, int max) {
        if (path.length() == max * 2) {
            res.add(path.toString());
            return;
        }
        if (open < max) {
            backtrack(res, path.append("("), open + 1, close, max);
            path.deleteCharAt(path.length()-1);
        }
        if (close < open) {
            backtrack(res, path.append(")"), open, close + 1, max);
            path.deleteCharAt(path.length()-1);
        }
    }
}
posted @ 2024-03-10 18:18  予真  阅读(3)  评论(0编辑  收藏  举报