首页 > 其他 > 详细

Generate Parentheses

时间:2017-11-07 17:24:54      阅读:246      评论:0      收藏:0      [点我收藏+]

描述

Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"

思路

该题目有一个规则是左括号个数得小于右括号个数,根据这个规则,可用通过动态规划来解决这个题目

代码

package com.lilei.myes.es.pack1107;

public class generate_parentheses {

	public static void main(String[] args) {

		int num = 4;

		genp("", num, num);
	}

	public static void genp(String s, int left, int right) {
		if (left > 0 && right > 0) {

			if (left == right) {
				genp(s + "(", left - 1, right);

			} else if (left < right) {
				genp(s + "(", left - 1, right);
				genp(s + ")", left, right - 1);
			}

		} else {
			for (int i = 0; i < right; i++)
				s = s + ")";
			System.out.println(s);
		}
	}

}

  

Generate Parentheses

原文:http://www.cnblogs.com/lilei2blog/p/7799586.html

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