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:
[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()”]

这道题的答案是很多种左右括号组合成的一个set,因为情况有很多种,所以常规的算法比较麻烦,所以采取递归的方法解决。算法的复杂度是O(n^2).

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> re;
        recursion(re,n,0,"");
        return re;
    }
    void recursion(vector<string> &re,int l,int r,string str){
        if(l == 0 && r == 0){
            re.push_back(str);
        }
        if(r>0) recursion(re,l,r-1,str+")");
        if(l>0) recursion(re,l-1,r+1,str+"(");//用掉一个左括号(l-1),可用的有括号就多了一个(r+1)
    }
};

举例n>3的时候,递归的过程如下:

                    "("
                  /      \
              "(("       "()"
             /    \     /    \
        "((("   "(()" "()("   **  //星号处,没有可用的右括号
        ...   

相关文章:

  • 2021-09-30
  • 2022-03-10
  • 2021-08-12
  • 2021-10-19
  • 2021-11-04
  • 2021-08-19
  • 2022-02-15
猜你喜欢
  • 2021-05-23
  • 2021-10-10
  • 2022-12-23
  • 2021-11-17
  • 2021-05-06
  • 2022-01-12
  • 2021-06-30
相关资源
相似解决方案