题目:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
链接:https://oj.leetcode.com/problems/generate-parentheses/
描述:生成包含n对括号的所有合法括号序列
解法:dfs
solution by python:
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
ans = []
self.generatePar(n,0,0,'',ans)
return ans
def generatePar(self,n, l, r, cur, ans):
if l==n and r==n:
ans.append(cur)
return
if l>r: self.generatePar(n,l,r+1,cur+')',ans)
if l<n: self.generatePar(n,l+1,r,cur+'(', ans)
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
dfs(0, n*2, 0, "", ans);
return ans;
}
void dfs(int cur, int n, int left, string par, vector<string> &ans){
if(cur >= n){
if(left == 0)
ans.push_back(par);
return;
}
dfs(cur+1, n, left+1, par+'(', ans);
if(left > 0)
dfs(cur+1, n, left-1, par+')', ans);
}
};