编程练习(三)

题目:一个组数:122345这6个数,打印出它所有可能的组合;要求4不能在第3位,3和5不能相连

public class ComboTest {
	public static void main(String... args) {
		int[] inArrays = {1, 2, 2, 3, 4, 5};
		int[] outArrays = new int[inArrays.length];
		go(inArrays[0], 1, inArrays, outArrays);
	}
	
	public static void go(int preNum, int level, int[] inArrays, int[] outArrays) {
		List<Integer> inList = new ArrayList<Integer>();
		for (int i = 0; i < inArrays.length; i++) {
			if (inList.contains(inArrays[i])) continue;
			if (level == 4 && inArrays[i] == 3) continue;
			if ((preNum == 3 && inArrays[i] == 5) 
					|| (preNum == 5 && inArrays[i] == 3)) 
				continue;
			outArrays[level - 1] = inArrays[i];
			inList.add(inArrays[i]);
			if (level == outArrays.length) {
				System.out.println(Arrays.toString(outArrays));
			} else {
				go(inArrays[i], level + 1, createNewArray(inArrays, i), outArrays);
			}
		}
	}

	private static int[] createNewArray(int[] inArrays, int index) {	
		int[] newArrays = new int[inArrays.length - 1];
		int newIndex = 0;
		for (int i = 0; i < inArrays.length; i++) {
			if (i == index) continue;
			newArrays[newIndex] = inArrays[i];
			newIndex++;
		}
		return newArrays;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值