标签:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Runtime: 4ms
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> result; 5 if(n <= 0) return result; 6 7 helper(result, "", n, n); 8 return result; 9 } 10 void helper(vector<string>& result, string temp, int left, int right){ 11 if(left > right) return; 12 13 if(left == 0 && right == 0){ 14 result.push_back(temp); 15 return; 16 } 17 18 if(left > 0) 19 helper(result, temp + "(", left - 1, right); 20 21 if(right > 0) 22 helper(result, temp + ")", left, right - 1); 23 24 } 25 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4873282.html