动态规划:硬币题目总结

  1. arr货币数组,其中值都是整数。再给定一个整数aim,每个值都被认为是一张货币,即便值相同的货币也认为每一张都是不同的,返回amin的方法数

  2. arr货币数组,其中值都是不重复整数。再给定一个整数aim,每个货币的张数是无限的,返回amin的方法数

  3. arr货币数组,其中值可以是是重复整数。再给定一个整数aim,每个相同值都被认为是同一种货币,返回amin的方法数

  4. arr货币数组,其中值都是不重复整数。再给定一个整数aim,每个货币的张数是无限的,返回构成aim的最少张数

从尝试模型来看

在这里插入图片描述

注:相同面值不同货币,相同面值相同货币,如果面值为2的货币有4张,相同面值相同货币,那么每个货币都有选和不选,面临 4 *2 =8个递归,而相同面值相同货币,每张性质一样,所以只能有4个递归

从尝试代码来看(尝试模型导致)

public static int process(int[] arr, int index, int rest) {
	if (rest < 0) {
		return 0;
	}
	if (index == arr.length) { // 没钱了!
		return rest == 0 ? 1 : 0;
	}
	return  process(arr,index+1,rest)+process(arr,index+1,rest-arr[index]);
}
public static int process(int[] arr, int index, int rest) {
	if (index == arr.length) { 
		return rest == 0 ? 1 : 0;
	}
	int ways = 0;
	for (int zhang = 0; zhang * arr[index] <= rest; zhang++) {
		ways += process(arr, index + 1, rest - (zhang * arr[index]));
	}
	return ways;
}
public static int process(int[] coins, int[] num, int index, int rest) {
	if (index == coins.length) {
		return rest == 0 ? 1 : 0;
	}
	int ways = 0;
	for (int zhang = 0; zhang * coins[index] <= rest && zhang <= num[index]; zhang++) {
		ways += process(coins, num, index + 1, rest - (zhang * coins[index]));
	}
	return ways;
}
public static int process(int[] arr, int index, int rest) {
	if (index == arr.length) {
		return rest == 0 ? 0 : Integer.MAX_VALUE;
	} else {
		int ans = Integer.MAX_VALUE;
		for (int zhang = 0; zhang * arr[index] <= rest; zhang++) {
			int next = process(arr, index + 1, rest - zhang * arr[index]);
			if (next != Integer.MAX_VALUE) {
				ans = Math.min(ans, zhang + next);
			}
		}
		return ans;
	}
}

从dp表看,尝试模型代码

在这里插入图片描述

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yilyil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值