LeetCode:Generate Parentheses
1116 ワード
Generate Parentheses
Total Accepted: 72319
Total Submissions: 207375
Difficulty: Medium
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:
Subscribe to see which companies asked this question
Hide Tags
Backtracking String
Hide Similar Problems
code:
Total Accepted: 72319
Total Submissions: 207375
Difficulty: Medium
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Subscribe to see which companies asked this question
Hide Tags
Backtracking String
Hide Similar Problems
code:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
backTra(res, "", 0, 0, n);
return res;
}
void backTra(vector<string> &v, string s, int left, int right, int max) {
if(2 * max == s.size()) {
v.push_back(s);
return;
}
if(left < max)
backTra(v, s + "(", left + 1, right, max);
if(right < left)
backTra(v, s + ")", left, right + 1, max);
}
};