标签:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
solution:DFS模版
package leetcode2; import java.util.ArrayList; public class Generate_parenthese { public static ArrayList<String> generateParenthesis(int n) { ArrayList<String> reArrayList=new ArrayList<String>(); String s=new String(); dfs(reArrayList,s,n,n); //DFS的模版递归 dfs(list<E>,E,deep,somethingConstant) return reArrayList; } public static void dfs(ArrayList<String> reArrayList, String s, int left,int right) { // TODO Auto-generated method stub // 先考虑deep极值,此处为left,right个数,直接return if(right<left){ return; } if(left==0&&right==0){ //当括号都用完时,将s存入list中 reArrayList.add(s); return; } if(left>0){ dfs(reArrayList, s+‘(‘, left-1, right); } if(right>0){ dfs(reArrayList, s+‘)‘, left, right-1); } } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(generateParenthesis(3)); } }
Leetcode22. Generate Parentheses
标签:
原文地址:http://www.cnblogs.com/joannacode/p/4389459.html