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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解题思路:本题就是个递归。
当左括号大于右括号的时候,可以选择左或者右
当左括号等于右括号的时候选择右=左
class Solution { public: void helper(vector<string>&res, int sum, int left, int right,string str){ if(left+right==sum){ if(left==right){ res.push_back(str); } return ; } if(left<right)return; helper(res,sum,left+1,right,str+"("); if(left>right){ helper(res,sum,left,right+1,str+")"); } } vector<string> generateParenthesis(int n) { vector<string>res; helper(res,2*n,0,0,""); return res; } };