Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 13, 2013 03:25
Show Gist options
  • Save zhoutuo/4942010 to your computer and use it in GitHub Desktop.
Save zhoutuo/4942010 to your computer and use it in GitHub Desktop.
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:
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> result;
calc(result, "", n, 0);
return result;
}
void calc(vector<string>& result, string cur,int left, int right) {
if(left == 0 and right == 0) {
result.push_back(cur);
return;
}
if(left > 0) {
calc(result, cur + '(', left - 1, right + 1);
}
if(right > 0) {
calc(result, cur + ')', left, right - 1);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment