积分组合问题

本文介绍了一种积分兑换策略,通过递归算法寻找最优的积分使用方案,以最小化剩余积分。探讨了产品数目可变性带来的挑战,并提出了解决方案。优化后的算法能够更高效地确定最佳兑换组合。

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

问题描述:给定一个积分总point,给定多个产品,每个产品需要相应数目的积分,用数组convertPoint[]表示,每种产品的兑换数量用数组convertCount[]表示,求如何兑换积分使得剩余积分最少。

示例:

input:

point = 19

convertPoint[] = {5,3}

output:

convertCount[] = {2,3}

 

解题思路:

问题还是很清晰明了的,我们采用的思想也很粗暴,尝试每一种组合方式,如 {0,0}, {0,1}, {0,2}, {0,3}...保证组合积分总数<=point即可,求得各种方案中剩余积分数量最少的组合。

关键难点在于产品数目的可变性,无法用固定的多个循环体来描述问题,一般这时候就需要用到递归了。

 

直接看代码:

	private static void calculateCash(int point,int i) {
        
        while(tempCount[i]*convertPoint[i]<=point){
        	if(i<convertPoint.length-1) {
        		calculateCash(point-tempCount[i]*convertPoint[i],i+1);
        	}else {
        		if((point-tempCount[i]*convertPoint[i])<rest) {
        			System.arraycopy(tempCount,0, convertCount, 0, tempCount.length);
        			rest = point-tempCount[i]*convertPoint[i];
        		}
        	}
        	tempCount[i]++;
        }
        tempCount[i] = 0;
    }

调用方法:

calculateCash(point,0);

需要两个额外的辅助变量

1 int rest = convertPoint[0];   //表示最少的积分剩余数

2 int tempCount[] = new int [convertPoint.length];   //用于表示目前的产品组合

 

优化:

对于最后一个产品数量可以不用从0开始向上加,直接取最大值;

即在此句if

if((point-tempCount[i]*convertPoint[i])<rest) {

前边添加

tempCount[i] = point / convertPoint[i];

优化后代码:

	private static void calculateCash(int point,int i) {
        
        while(tempCount[i]*convertPoint[i]<=point){
        	if(i<convertPoint.length-1) {
        		calculateCash(point-tempCount[i]*convertPoint[i],i+1);
        	}else {
        		tempCount[i] = point / convertPoint[i];
        		if((point-tempCount[i]*convertPoint[i])<rest) {
        			System.arraycopy(tempCount,0, convertCount, 0, tempCount.length);
        			rest = point-tempCount[i]*convertPoint[i];
        		}
        	}
        	tempCount[i]++;
        }
        tempCount[i] = 0;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值