问题描述:
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
问题分析:
深度优先遍历DFS,能加“(”就加,能加“)”就加“)”
问题求解:
class Solution {
private:
void dfs( vector<string>& v, string str, int n, int m){
if( n == 0 && m == 0){
v.push_back(str);
return;
}
if(m > 0) dfs(v, str + ")", n, m-1);
if(n > 0) dfs(v, str + "(", n - 1, m+1);
}
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
dfs(res, "", n, 0);
return res;
}
};
这题没有思路,以上答案参考讨论组里的,比较容易懂。