码迷,mamicode.com
首页 > 编程语言 > 详细

【Leetcode】Generate Parentheses in JAVA

时间:2014-11-29 10:32:48      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   递归   dfs   

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思想做递归就好了,记好了先写base case,left,right走过一遍了,可以把这个String加进list

import java.util.ArrayList;
import java.util.List;

public class generateParentheses {
	public static void main(String args[]){
		generateParentheses gp = new generateParentheses();
		System.out.println(gp.generateParenthesis(3));
	}
	public List<String> generateParenthesis(int n) {
		if(n<=0)	return null;
		ArrayList<String>	list = new ArrayList<String>();
		String str = new String();
		dfs(list,str,n,n);
		return list;
    }
	
	private void	dfs(ArrayList<String> list, String str, int left, int right){
		if(left>right)	return;//problem with ")("
		if(left==0&&right==0){
			list.add(str);
		}
		if(left>0)	dfs(list,str+"(",left-1,right);
		if(right>0)	dfs(list, str+")",left,right-1);
	}
}


【Leetcode】Generate Parentheses in JAVA

标签:java   leetcode   递归   dfs   

原文地址:http://blog.csdn.net/qbt4juik/article/details/41592983

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!