首页 > 其他 > 详细

22. Generate Parentheses产生所有匹配括号的方案

时间:2020-07-28 11:17:30      阅读:74      评论:0      收藏:0      [点我收藏+]

 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:

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

思路:
不知道DFS应该写什么。其实就是把dfs代入不同的数值,再写一遍就行了。不同条件的可以分开写

dfs字符串的题目,一般有个String currentString。这里要判断左右开口数,还要加open close变量

技术分享图片
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList<>();
        
        //cc
        if (n < 0) return results;
        
        //dfs
        dfs(n, 0, 0, "", results);
            
        //return
        return results;
    }
    
    public void dfs(int n, int open, int close, String cur, List<String> results) {
       //exit
        if (cur.length() >= 2 * n) {
            results.add(cur);
            return ;
        }
        
        if (open < n)
            dfs(n, open + 1, close, cur + ‘(‘, results);
        if (close < open)
            dfs(n, open, close + 1, cur + ‘)‘, results);
    }
}
View Code

 



22. Generate Parentheses产生所有匹配括号的方案

原文:https://www.cnblogs.com/immiao0319/p/13388355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!