【递归到动态规划】:凑硬币问题

题目

有这么一组硬币:7,3,50,100,且每个硬币有无数多个,问有多少种方法能够凑齐1000元钱

代码

递归法

递归法的思路就是暴力枚举,比如这一次在arr位置选0个硬币,1个硬币直到10个硬币,剩下的位置也做相同的选择。剩余到最后一个位置了,就判断是否凑齐到1000

//arr中都是正数且无重复值,返回组成aim的方法数
public static int ways(int[] arr, int aim) {
    
    
	if ( arr == null || arr. length == 0 || aim < 0) {
    
    
		return 0;
	}
		return process( arr, 0, aim);
}
	//可以自由使用arr[index.. .]所有的面值,每一种面值都可以使用任意张,//组成rest,有多少种方法
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;
}

动态规划版

递归版确实很妙
在这里插入图片描述
这里把枚举直接也缓存了。先举一个具体的例子:比如要填充arr[10][100],它是拿第11列的元素累加得来,c,b,a的差值就是这个硬币的面值,第[10][100]个是要累加到a,而第[10][97]是累加到b,所以我们得到arr[10][100]只需要arr[10][97]+arr[11][100]即可。其余同理。

public static int dp(int[] arr, int aim) {
    
    
	if (aim == 0) {
    
    
		return 1;
	}
	int N = arr.length;
	int[][] dp = new int[N + 1][aim + 1];
	dp[N][0] = 1;
	for (int index = N - 1; index >= 0; index--) {
    
    
		for (int rest = 0; rest <= aim; rest++) {
    
    
			if(rest-arr[index]>=0) {
    
    
				dp[index][rest]=dp[index + 1][rest]+dp[index][rest-arr[index]];
			}else {
    
    
				dp[index][rest]=dp[index + 1][rest];
			}
			//dp[index][rest] = dp[index + 1][rest] + (rest - arr[index] >= 0 ? dp[index + 1][rest - arr[index]] : 0);
		}
	}
	return dp[0][aim];
}

猜你喜欢

转载自blog.csdn.net/VanGotoBilibili/article/details/115279300