LeetCode-22.Generate Parentheses
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
使用DFS+剪枝
1 class Solution {//DFS 剪枝 mytip 2 public List<String> generateParenthesis(int n) { 3 List<String> re = new ArrayList<>(); 4 generate(n,n,re,""); 5 return re; 6 7 } 8 private void generate(int left,int right,List<String> re ,String s){ 9 if(0==left&&0==right){ 10 re.add(s); 11 return; 12 } 13 if(left>0){ 14 generate(left-1,right,re,s+"("); 15 } 16 if(left<right){ 17 generate(left,right-1,re,s+")"); 18 } 19 } 20 }
相关题
有效括号匹配 LeetCode20 https://www.cnblogs.com/zhacai/p/10429168.html