[LeetCode]Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
回溯的方法,递归实现。
1 class Solution { 2 private: 3 public: 4 void generate(int left,int right,string s,vector<string>& result) 5 { 6 if(left==0 && right==0) 7 { 8 result.push_back(s); 9 } 10 if(left>0) 11 { 12 generate(left-1,right,s+'(',result); 13 } 14 if(right>0 && left<right) 15 { 16 generate(left,right-1,s+')',result); 17 } 18 } 19 vector<string> generateParenthesis(int n) { 20 string s=""; 21 vector<string> result; 22 generate(n,n,s,result); 23 return result; 24 } 25 };