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:

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

这是一个排列组合的问题, 所有组合的个数其实是一个卡特兰数

本题有简单解法

依据:

其实对于某个合法的字符串,我们可以发现从合法字符串的任何一个位置看,“(”的数目 >= ")"的数目,即剩余的“(”的数目 <= 剩余的")"数目

代码:

public List<String> generateParenthesis(int n) {
		List<String> result = new ArrayList<String>();
		doGenerateParenthesis(result, "(", 1, 0, n);
		return result;
    }
	
	private void doGenerateParenthesis (List<String> result, String str, 
			int leftParNum, int rightParNum, int n) {
		if(leftParNum==n && rightParNum==n) {
			result.add(str);
			return ;
		}
		if(leftParNum < rightParNum) {
			return ;
		}
		if(leftParNum < n) {
			doGenerateParenthesis(result, str+"(", leftParNum+1, rightParNum, n);
		}
		if(rightParNum < n) {
			doGenerateParenthesis(result, str+")", leftParNum, rightParNum+1, n);
		}
	}

另一种比较好的写法

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> rst = new ArrayList<String>();
        if(n <= 0) {
            return rst;
        }
        getPair(rst, "", n, n);
        return rst;
    }
    
	public void getPair( ArrayList<String> rst , String s, int left, int right) {
		if(left > right || left < 0 || right < 0) {
			return; 	
		}
		if(left == 0 && right == 0) {
			rst.add(s);
			return;
		}

		getPair(rst, s + "(", left - 1, right);
		getPair(rst, s + ")", left, right - 1);
	}
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值