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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"
]
import java.util.ArrayList; import java.util.List; /** * Created by lxw, liwei4939@126.com on 2018/3/5. */ public class Generateparenthese { public List<String> generateParenthesis(int n){ if (n <= 0){ return new ArrayList<>(); } ArrayList<String> res = new ArrayList<>(); dfs(res, "", n, n); return res; } void dfs(ArrayList<String> res, String str, int left, int right){ // left 表示还需要的左括号数 // right 表示还需要的右括号数量 if (left > right){ return; } if (left == 0 && right == 0){ res.add(str); } if (left > 0){ dfs(res, str + "(", left -1, right); } if (right > 0){ dfs(res, str + ")", left, right-1); } } public static void main(String[] args){ Generateparenthese tmp = new Generateparenthese(); System.out.println(tmp.generateParenthesis(3)); } }