leetcode128-generate-parentheses
题目描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()(())", "()()()"
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
示例2
输出
复制["(())","()()"]
class Solution {
public:
/**
*
* @param n int整型
* @return string字符串vector
*/
void generateParenthesisAux(int n,int x ,int y,string s,vector<string> &ans){
if (y==n) ans.push_back(s);
if (x<n) generateParenthesisAux(n, x+1, y, s+"(", ans);
if (x>y) generateParenthesisAux(n, x, y+1, s+")", ans);
}
vector<string> generateParenthesis(int n) {
// write code here
vector <string> ans;
generateParenthesisAux(n,0,0,"",ans);
return ans;
}
};