首页 > 代码库 > [Leetcode] Generate Parentheses
[Leetcode] 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution:
1 public class Solution { 2 public List<String> generateParenthesis(int n) { 3 List<String> result=new ArrayList<String>(); 4 dfs(n,n,result,""); 5 return result; 6 } 7 8 private void dfs(int left, int right, List<String> result, String temp) { 9 // TODO Auto-generated method stub10 if(right<0||left<0)11 return;12 if(right==0&&left==0)13 result.add(temp);14 if(left>0)15 dfs(left-1, right, result, temp+"(");16 if(right>left)17 dfs(left, right-1, result, temp+")");18 }19 }
[Leetcode] Generate Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。