首页 > 其他 > 详细

Generate Parentheses

时间:2015-06-03 02:13:52      阅读:231      评论:0      收藏:0      [点我收藏+]

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

?

public class Solution {
    public List<String> generateParenthesis(int n) {
    	List<String> list = new ArrayList<String>();
    	solve(n,0,0,"",list);
    	return list;
    }

	private void solve(int n, int left, int right, String string, List<String> list) {
		if (left==n && right==n) {
			list.add(string);
		}
		if (left < n) {
			solve(n,left+1,right,string+‘(‘,list);
		}
		if (right<n && left>right) {
			solve(n,left,right+1,string+‘)‘,list);
		}
	}
}

?

Generate Parentheses

原文:http://hcx2013.iteye.com/blog/2216342

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!