[LeetCode]Generate Parentheses题解

来源:互联网 发布:c语言乘方 编辑:程序博客网 时间:2024/06/03 19:26

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的时候,递归的过程如下:

                    "("                  /      \              "(("       "()"             /    \     /    \        "((("   "(()" "()("   **  //星号处,没有可用的右括号        ...   
原创粉丝点击