9.9递归和动态规划(十)——堆箱子

本文探讨了如何使用递归和动态规划解决堆箱子的问题,详细介绍了两种不同的解题思路,分别是利用递归的直观方法和采用动态规划以优化效率的策略。

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

/**
 * 功能:给你一堆n个箱子,箱子宽wi,高hi,深di。箱子不能翻转,将箱子堆起来时,下面箱子的宽度、高度和深度必须大于上面的箱子。
 * 实现方法:搭出最高的一堆箱子,箱子堆的高度为每个箱子高度的总和。

 */


两种方法:

方法一:递归法

	//递归法
	public static ArrayList<Box> createStackR(Box[] boxes,Box bottom){
		int maxHeight=0;
		ArrayList<Box> maxStack=null;
		
		for(int i=0;i<boxes.length;i++){
			if(boxes[i].canBeAbove(bottom)){
				ArrayList<Box> newStack=createStackR(boxes,boxes[i]);
				int newHeight=stackHeight(newStack);
				
				if(newHeight>maxHeight){
					maxHeight=newHeight;
					maxStack=newStack;
				}
			}
		}
		
		if(maxStack==null)
			maxStack=new ArrayList<Box>();
		
		if(bottom!=null)
			maxStack.add(0,bottom);
		
		return maxStack;
	}
	
	public static int stackHeight(ArrayList<Box> stack){
		int height=0;		
		for(in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值