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:
"((()))", "(()())", "(())()", "()(())", "()()()"
很简单的递归实现
class Solution { public: void Sub(vector<string>* ret,string* s,int level,int left,int current){ if(left==0){ while(level>0){ (*s)[current]=')'; level--; current++; } (*ret).push_back(*s); } else{ (*s)[current]='('; Sub(ret,s,level+1,left-1,current+1); if(level!=0){ (*s)[current]=')'; Sub(ret,s,level-1,left,current+1); } } } vector<string> generateParenthesis(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> ret; string s; s.resize(2*n); Sub(&ret,&s,0,n,0); return ret; } };