标签:
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 参考:http://blog.csdn.net/yangliuy/article/details/41170599
public class Solution { public static List<String> ans; public List<String> generateParenthesis(int n) { ans=new ArrayList<String>(); if(n<=0) return ans; dfs("",n,n); return ans; } public void dfs(String str,int left,int right){ if(left>right){ return ; } if(left==0&&right==0){ ans.add(str); } if(left>0){ dfs(str+"(",left-1,right); } if(right>0){ dfs(str+")",left,right-1); } } }
LeetCode 22 Generate Parentheses
标签:
原文地址:http://www.cnblogs.com/gonewithgt/p/4572864.html