[LeetCode-22] 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 public: 3 vector<string> result; 4 5 bool is_format(const string& str) { 6 int left = 0; 7 for (int i = 0; i < str.length(); ++i) { 8 if ('(' == str[i]) { 9 ++left; 10 } else if (--left < 0) { 11 return false; 12 } 13 } 14 return true; 15 } 16 17 void append_str(string str, int left, int right) { 18 if ((0 == left) && (0 == right) && is_format(str)) { 19 result.push_back(str); 20 return; 21 } 22 if (!is_format(str)) { 23 return; 24 } 25 bool is_append = false; 26 27 if (left > 0) { 28 str.append("("); 29 append_str(str, left - 1, right); 30 is_append = true; 31 } 32 if (right > 0) { 33 if (is_append) { 34 str.erase(str.length() - 1, 1); 35 } 36 str.append(")"); 37 append_str(str, left, right - 1); 38 } 39 } 40 41 vector<string> generateParenthesis(int n) { 42 // Start typing your C/C++ solution below 43 // DO NOT write int main() function 44 string str = ""; 45 result.clear(); 46 append_str(str, n, n); 47 return result; 48 } 49 };