题目来源:leetcode
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://blog.csdn.net/uknowfigo/article/details/44095097
想到了回溯,写不出dfs,尴尬如图:
代码
/**
* 递归
* Created by a819 on 2017/8/17.
*/
import java.util.*;
public class GenerateParenthese {
public List<String> generateParenthesis(int n) {
List<String> result=new LinkedList<>();
if (n==0)
return result;
dfs(result,"",n,n);
return result;
}
public void dfs(List<String> result,String s,int left,int right){
if (left>right||left<0||right<0)
return;
if (left==0&&right==0)
result.add(s);
dfs(result,s+"(",left-1,right);
dfs(result,s+")",left,right-1);
}
}