leetcode--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:

[

  "((()))",

  "(()())",

  "(())()",

  "()(())",

  "()()()"

]

解答:

C++版本

  

  void search(int left, int right, string path, vector& v) {
        if(!left && !right) { v.push_back(path); return ; }
        if(left > 0) search(left-1, right, path+"(", v);
        if(left < right) search(left, right-1, path+")", v);
    }
    vector generateParenthesis(int n) {
        vector v;
        search(n, n, "", v);
        return v;
    }


Java版本

 

private void helper(List res, String present, int left, int right) {
    if (right == 0) {
        res.add(present);
    }
    if (left > 0) {
        helper(res, present + "(", left - 1, right);
    }
    if (right > left) {
        helper(res, present + ")", left, right - 1);
    }
}
public List generateParenthesis(int n) {
    List res = new ArrayList();
    if (n == 0) {
        return res;
    }
    helper(res, "", n, n);
    return res;
}


思路:

使用递归的方式产生括号

(  -> (( 和 ()

 

      (( ->  (((和(()

      () ->  ()(      不能产生())

 

            ((( -> ((((和((()

            (() -> (())和(()(

            ()( -> ()()和()((

                  ... ...

 

 

 

你可能感兴趣的:(算法)