首页 > 代码库 > [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