Created
February 13, 2013 03:25
-
-
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: "((()))", "(()())", "(())()", "()(())", "()()()"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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