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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:这道题给你n对括号,生成所有合法的括号规则。有如下规则:左括号和右括号的数量都为n时,将生成的括号push到result里;左括号的数量小于n,插入str,然后递归;当右括号的数量小于左括号的数量,将')'插入str中,然后递归。
class Solution { public: void MatchNums(int n,vector<string> &result,string &str,int nLeftBrackts,int nRightBrackts) { if(nLeftBrackts==n&&nRightBrackts==n) { result.push_back(str); return; } if(nLeftBrackts<n) { str.push_back('('); MatchNums(n,result,str,nLeftBrackts+1,nRightBrackts); str.pop_back(); } if(nRightBrackts<nLeftBrackts) { str.push_back(')'); MatchNums(n,result,str,nLeftBrackts,nRightBrackts+1); str.pop_back(); } } vector<string> generateParenthesis(int n) { vector<string> result; string str; MatchNums(n,result,str,0,0); return result; } };