Code 排列小球(Ways to arrange Balls such that adjacent balls are of different types)

在这里插入图片描述

举例:

input: 2 1 1
output: 6

使用递归的方法来求解:

public class Main { 
	
	// Returns count of arrangements 
	// where last placed ball is 
	// 'last'. 'last' is 0 for 'p', 
	// 1 for 'q' and 2 for 'r' 
	static int countWays(int p, int q, int r, int last) 
	{ 
		// if number of balls of any 
		// color becomes less than 0 
		// the number of ways arrangements is 0. 
		if (p < 0 || q < 0 || r < 0) 
			return 0; 
	
		// If last ball required is 
		// of type P and the number 
		// of balls of P type is 1 
		// while number of balls of 
		// other color is 0 the number 
		// of ways is 1. 
		if (p == 1 && q == 0 && r == 0 && last == 0) 
			return 1; 
	
		// Same case as above for 'q' and 'r' 
		if (p == 0 && q == 1 && r == 0 && last == 1) 
			return 1; 
		if (p == 0 && q == 0 && r == 1 && last == 2) 
			return 1; 
	
		// if last ball required is P 
		// and the number of ways is 
		// the sum of number of ways 
		// to form sequence with 'p-1' P 
		// balls, q Q Balls and r R balls 
		// ending with Q and R. 
		if (last == 0) 
			return countWays(p - 1, q, r, 1) + 
				countWays(p - 1, q, r, 2); 
	
		// Same as above case for 'q' and 'r' 
		if (last == 1) 
			return countWays(p, q - 1, r, 0) + 
				countWays(p, q - 1, r, 2); 
		
		if (last == 2) 
			return countWays(p, q, r - 1, 0) + 
				countWays(p, q, r - 1, 1); 
	
		return 0; 
	} 
	
	// Returns count of required arrangements 
	static int countUtil(int p, int q, int r) { 
		// Three cases arise: 
		return countWays(p, q, r, 0) + // Last required balls is type P 
			countWays(p, q, r, 1) + // Last required balls is type Q 
			countWays(p, q, r, 2); // Last required balls is type R 
	} 
	
	// Driver code 
	public static void main(String[] args) 
	{ 
		int p = 2, q = 1, r = 1; 
		System.out.print(countUtil(p, q, r)); 
	} 
} 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值