当前位置:网站首页>22.括号生成

22.括号生成

2022-08-10 00:32:00 ⁡⁢等风来

题目

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

示例 1:

输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:

输入:n = 1
输出:[“()”]

代码

//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
    
    public List<String> generateParenthesis(int n) {
    
        List<String> res=new ArrayList<>();
        if (n <= 0) return res;
        dfs(n, "", res, 0, 0);
        return res;
    }
    private void dfs(int n, String path, List<String> res, int open, int close){
    
        if(open > n || open < close) return;
        if(path.length() == 2 * n){
    
            res.add(path);
            return;
        }
        dfs(n, path+"(", res, open + 1, close);
        dfs(n, path+")", res, open, close + 1);
    }

    public static void main(String[] args) {
    
        System.out.println(new Solution().generateParenthesis(2));
    }
}

笔记

剪枝策略

所谓的剪枝策略就是在生成树的过程中避免生成一些无意义的分支,比如上边的 if(open > n || open < close) return;

回溯

所谓的回溯就是在递归到递归出口时,往回走的过程

ps:代码是照着别人的敲得,其实还是不太理解递归,恼火

原网站

版权声明
本文为[⁡⁢等风来]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_41588302/article/details/126226688