CCI 9.6 括号全部组合

本文介绍了一种生成n对括号所有有效组合的算法,并提供了详细的Java实现代码。该算法通过递归方式确保左括号始终不小于右括号的数量,从而避免无效组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现一种算法,打印n对括号的全部有效组合(即左右括号正确配对)。

示例

输入:3

输出:((())),(()()),(())(),()(()),()()()。

import java.util.ArrayList;

public class CCI_9_6 {
	
	public static ArrayList<String> genePare(int n){
		ArrayList<String> result = new ArrayList<String>();
		if(n <= 0)
			return result;
		genePare(n, 0, 0, "", result);
		return result;
	}
	private static void genePare(int n, int leftCount, int rightCount, String str, ArrayList<String> result){
		//end
		if(rightCount == n){
			String temp = new String(str);
			result.add(temp);
			return;
		}
		//add left
		if(leftCount < n){
			genePare(n, leftCount+1, rightCount, str+"(", result);
		}
		//add right
		if(rightCount < leftCount){
			genePare(n, leftCount, rightCount+1, str+")", result);
		}
	}

	public static void main(String[] args) {
		int n = 3;
		ArrayList<String> result = genePare(n);
		for(String item : result){
			System.out.println(item);
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值