算法之回溯算法-24点问题

24点问题:收取四张牌加起来等于24点的可能有哪些?

/**
 * 
 * @author 陈鑫
 * 回溯解决24点问题
 *
 */
public class TwentyFourPoints {
	
	public static void scratchCard(ArrayList<Integer> cardList,ArrayList<Integer> handList) {
		int length = handList.size();//手牌数量
		Integer count = 0;//总点数
		//计算手牌总点数
		if(length != 0 || length < 5) {
			for(Integer card:handList) {
				count += card;
			}
		}
		//当手牌数量小于4或者手牌总点数大于等于24时抓牌
		if(count < 24 && length < 4) {
			for(Integer card : cardList){
				//重新定义handList
				ArrayList<Integer> newHandList = new ArrayList<Integer>();
				//添加手牌
				newHandList.addAll(handList);
				newHandList.add(card);
				//注意:方法传参传的是ArrayList的对象的引用地址,会导致原有的List集合会重复添加
				//递归抓牌
				scratchCard(cardList,newHandList);
			}
		}else if(count == 24 && length == 4) {
			//当手牌数量等于4并且总点数等于24点的时候打印
			for(Integer cardPrint:handList) {
				System.out.print(cardPrint + ",");
			}
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		//牌堆
		ArrayList<Integer> cardList = new ArrayList<Integer>();
		//牌堆初始化
		for(int i=1;i<11;i++) {
			cardList.add(i);
		}
		//手牌
		ArrayList<Integer> handList = new ArrayList<Integer>();
		//抓牌
		scratchCard(cardList,handList);	
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回溯算法是一种解决问题算法思想,它通过不断地尝试所有可能的解决方案来寻找问题的最优解。而装载问题回溯算法的一个经典应用,它是指在给定一些集装箱和一艘载重量为C的轮船的情况下,如何将这些集装箱装载到轮船上,使得轮船的载重量最大。 具体来说,装载问题可以通过回溯算法来解决。我们可以定义一个递归函数来尝试所有可能的装载方案,每次递归时,我们可以选择将当前集装箱装载到轮船上或者不装载,然后继续递归下去。当所有集装箱都被考虑过后,我们就可以得到一个装载方案,然后比较这个方案的载重量和当前最优解的载重量,如果更优则更新最优解。 下面是一个简单的装载问题回溯算法实现: ```c #include <stdio.h> #define MAX_N 100 int n; // 集装箱数量 int c; // 轮船载重量 int w[MAX_N]; // 集装箱重量 int best[MAX_N]; // 当前最优解 int cur[MAX_N]; // 当前解 int cur_weight; // 当前载重量 int best_weight; // 当前最优解的载重量 void backtrack(int i) { if (i == n) { // 所有集装箱都被考虑过 if (cur_weight > best_weight) { // 更新最优解 best_weight = cur_weight; for (int j = 0; j < n; j++) { best[j] = cur[j]; } } return; } if (cur_weight + w[i] <= c) { // 装载当前集装箱 cur[i] = 1; cur_weight += w[i]; backtrack(i + 1); cur_weight -= w[i]; } cur[i] = 0; // 不装载当前集装箱 backtrack(i + 1); } int main() { scanf("%d%d", &n, &c); for (int i = 0; i < n; i++) { scanf("%d", &w[i]); } backtrack(0); printf("最大载重量为:%d\n", best_weight); printf("装载方案为:"); for (int i = 0; i < n; i++) { if (best[i]) { printf("%d ", i + 1); } } printf("\n"); return 0; } ``` 在这个实现中,我们使用了一个数组`cur`来记录当前的解,使用`cur_weight`来记录当前的载重量,使用`best`来记录当前最优解,使用`best_weight`来记录当前最优解的载重量。在回溯函数`backtrack`中,我们首先判断是否可以装载当前集装箱,如果可以则装载,然后递归下去;如果不可以则不装载,然后递归下去。当所有集装箱都被考虑过后,我们就可以得到一个装载方案,然后比较这个方案的载重量和当前最优解的载重量,如果更优则更新最优解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值