来源:Leetcode
原帖:http://oj.leetcode.com/problems/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:
"((()))", "(()())", "(())()", "()(())", "()()()"
代码:
原帖:http://oj.leetcode.com/problems/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:
"((()))", "(()())", "(())()", "()(())", "()()()"
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generateParenthesisHelper(n, n, "", result);
return result;
}
void generateParenthesisHelper(int left, int right, string s, vector<string> &result) {
if (left == 0 && right == 0) {
result.push_back(s);
}
if (left > 0) {
generateParenthesisHelper(left - 1, right, s + "(", result);
}
if (right > left) {
generateParenthesisHelper(left, right - 1, s + ")", result);
}
}
};
No comments:
Post a Comment