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

 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

 



posted @ 2020-07-27 23:16  苗妙苗  阅读(104)  评论(0编辑  收藏  举报