22. Generate Parentheses (DFS, String)

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:

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

思路:

1. 违规情况:左括号的剩余大于右括号。

2. 当左括号剩余大于1 首先加入左括号,然后回溯,如果此时左括号剩余小于右括号就加入右括号。

3. 直到全部剩余0返回。

注意:

doGenerate(cur,res,left-1,right);里面不能left--否则会死循环,因为是递归之后才自减!!!

 public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        if(n<=0)
            return res;
        doGenerate("",res,n,n);
        return res;
    }
    private void doGenerate(String tmp, List<String> res,int left, int right){
        if(left==0 && right==0){
            res.add(tmp);
            return;
        }
        if(left>0){
            String cur = tmp + "(";
            doGenerate(cur,res,left-1,right);
            tmp = cur.substring(0, cur.length()-1);
        }
        if(left<right){
            String cur = tmp + ")";
            doGenerate(cur,res,left,right-1);
            tmp = cur.substring(0, cur.length()-1);
        }
    }

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/86034150