DP7 两道换硬币的问题 Coin Change @geeksforgeeks

高级数据结构与算法习题(9) 解析:F。设S是活动选择问题中的一组活动。那么,S的相互兼容活动必须有一些最大大小的子集,其中包括最早完成的活动a​m。但是并不是最早完成活动am​必须包括在S的所有相互兼容活动的最大规模子集中。解析:T。根据哈夫曼树的性质,对于字符集大小为 n 的情况,任何一个字符的最优编码长度不会超过 n-1。这是因为在哈夫曼树中,从根节点到叶子节点的路径长度即为该字符的编码长度,而哈夫曼树的最短路径长度为 1,最长路径长度为 n-1。 阅读详情

1 Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.

两种思路:

1)http://www.cs.ucf.edu/~dmarino/ucf/cop3530/lectures/COP3530DynProg02.doc

特别注意到换完的硬币是没有顺序的,所以要impose order


2)http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/

http://www.cnblogs.com/python27/p/3303721.html

http://www.mathblog.dk/project-euler-31-combinations-english-currency-denominations/


考虑是否取最后一个硬币,转换为背包问题

package DP;

import java.util.Arrays;

/**
Given a value N, if we want to make change for N cents, 
and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, 
how many ways can we make the change? The order of coins doesn’t matter.

 */
public class CoinChange1 {

	public static int MEM[] = new int[10001];   // Can support up to 10000 peso value
     
    public static void main(String[] args) {
    	
    	int coins[] = {1, 2, 3};  // Available coin denominations
    	Arrays.sort(coins);
    	int coinKinds = coins.length;
    	int sum = 4;
    	System.out.println(countRec_1st(coins, coinKinds, sum, coins[coins.length-1]));
    	System.out.println(countRec_2nd(coins, coinKinds, sum));
    	System.out.println(countDP_1st(coins, coinKinds, sum));
    	System.out.println(countDP2D_2nd(coins, coinKinds, sum));
    	System.out.println(countDP1D_2nd(coins, coinKinds, sum));
    }
    
  //====================================第一种思路
    /*
     max 用来保持order,否则就会有重复,如(1,2),(2,1)
     */
    public static int countRec_1st(int coins[], int coinKinds, int sum, int max){
    	if(sum < 0){
    		return 0;
    	}
    	if(sum == 0){
    		return 1;
    	}
    	
    	int ways = 0;
    	for(int i=0; i<coinKinds; i++){
    		if(max >= coins[i]){
    			ways += countRec_1st(coins, coinKinds, sum-coins[i], coins[i]);
    		}
    	}
    	return ways;
    }
    
    
    // http://www.cnblogs.com/python27/p/3303721.html
    // dp[i][j] = sum(dp[i-1][j-k*coins[i-1]]) for k = 1,2,..., j/coins[i-1]
    // dp[0][j] = 1 for j = 0, 1, 2, ..., sum
    public static int countDP_1st(int[] coins, int coinKinds, int sum){
    	int[][] dp = new int[coinKinds+1][sum+1];
    	
    	for(int i=0; i<=coinKinds; i++){
    		for(int j=0; j<=sum; j++){
    			dp[i][j] = 0;
    		}
    	}
    	for(int i=0; i<=coinKinds; i++){
    		dp[i][0] = 1;
    	}
    	
    	for(int i=1; i<=coinKinds; i++){	// 币的面值
    		for(int j=1; j<=sum; j++){		// 要凑成的数量
    			dp[i][j] = 0;
    			for(int k=0; k<=j/coins[i-1]; k++){
    				dp[i][j] += dp[i-1][j-k*coins[i-1]];
    			}
    		}
    	}
    	
    	return dp[coinKinds][sum];
    }


    //====================================第二种思路
    
    // Return the count of ways we can sum coins[0...m-1] coins to get sum 
    public static int countRec_2nd(int coins[], int coinKinds, int sum){
    	if(sum == 0){	// If n is less than 0 then no solution exists
    		return 1;
    	}
    	if(sum < 0){	// If n is less than 0 then no solution exists
    		return 0;
    	}
    	if(coinKinds<=0 && sum>=1){	// If there are no coins and n is greater than 0, then no solution exist
    		return 0;
    	}
    	// count is sum of solutions (i) including coins[m-1] (ii) excluding coins[m-1]
    	// 两种情况:
    	// 1. 不使用最后一个硬币,因此实际上就是用少了最后一个硬币的coins来凑sum
    	// 2.使用最后一个硬币,因此sum的总数减少,因为每个硬币都有无数个,所以m不变
    	return countRec_2nd(coins, coinKinds-1, sum) + countRec_2nd(coins, coinKinds, sum-coins[coinKinds-1]);
    }
    
    
    public static int countDP2D_2nd(int[] coins, int coinKinds, int sum){
    	// We need n+1 rows as the table is constructed in bottom up manner using 
        // the base case 0 value case (n = 0)
    	int[][] dp = new int[sum+1][coinKinds];
    	
    	// Fill the entries for 0 value case (sum = 0)
    	for(int i=0; i<coinKinds; i++){
    		dp[0][i] = 1;
    	}
    	
    	// Fill rest of the table entries in bottom up manner  
    	for(int i=1; i<=sum; i++){		// sum
    		for(int j=0; j<coinKinds; j++){		// coins m
    			// Count of solutions including S[j]
    			int x = (i-coins[j]>=0) ? dp[i-coins[j]][j] : 0;	// 要满足i-coins[j]>=0
    			// Count of solutions excluding S[j]
    			int y = (j>=1) ? dp[i][j-1] : 0;	// 要满足j-1>=0
    			dp[i][j] = x + y;
    		}
    	}
    	return dp[sum][coinKinds-1];
    }
    
    
    public static int countDP1D_2nd(int[] coins, int coinKinds, int sum){
    	
    	// dp[i] will be storing the number of solutions for
        // value i. We need n+1 rows as the table is constructed
        // in bottom up manner using the base case (n = 0)
    	int[] dp = new int[sum+1];
    	
    	dp[0] = 1;	// Base case (If given value is 0)
    	// Pick all coins one by one and update the table[] values
        // after the index greater than or equal to the value of the
        // picked coin
    	for(int i=0; i<coinKinds; i++){			// coins m
    		for(int j=coins[i]; j<=sum; j++){	// sum
    			dp[j] += dp[j-coins[i]];
    		}
    	}
    	return dp[sum];
    }
    
}

2 What is the smallest number of coins to change? 如果换,最少会有多少枚硬币?

http://www.columbia.edu/~cs2035/courses/csor4231.F11/dynamic.pdf

C[p] = min{C[p-di]+1} 


package DP;

import java.util.Arrays;

/**
A country has coins with denominations
1 = d1 < d2 < · · · < dk.
  
You want to make change for n cents, using the smallest number
 
 */
public class CoinChange2 {

	public static int MEM[] = new int[10001];   // Can support up to 10000 peso value
    public static int coins[] = {1, 2, 3};  // Available coin denominations
     
    public static void main(String[] args) {
    	int n = 4;
        System.out.println(minCoins(n));
        System.out.println(minCoins_DP(n));
    }
    
    
    // 记忆化搜索,top-down 递归
    public static int minCoins(int n) {
        if(n < 0)
            return Integer.MAX_VALUE -1;
        else if(n == 0)
            return 0;
        else if(MEM[n] != 0)    // If solved previously already
            return MEM[n];
        else {
            // Look for the minimal among the different denominations
            MEM[n] = 1+minCoins(n-coins[0]);
            for(int i = 1; i < coins.length; i++)
                MEM[n] = Math.min(MEM[n], 1+minCoins(n-coins[i]));
            return MEM[n];
        }
    }

    // bottom-up DP
	public static int minCoins_DP(int n){
		int[] minCoins = new int[n+1];
		Arrays.fill(minCoins, Integer.MAX_VALUE);
		
		// 第一个硬币
		minCoins[0] = 0;
		
		// 算出n前的每一个可换硬币的数量
		for(int i=1; i<=n; i++){
			// 根据递推公式,看看硬币可拆分的可能性
			for(int j=0; j<coins.length; j++){
				if(coins[j] <= i){
					minCoins[i] = Math.min(minCoins[i], 1+minCoins[i-coins[j]]);
				}
			}
		}
		
		return minCoins[n];
	}
	
}

Python入门基础教程(非常详细) Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,坚持「极简主义」。Python类库(模块)极其丰富,这使得Python几乎无所不能,不管是传统的Web开发、PC软件开发、Linux运维,还是当下火热的机器学习、大数据分析、网络爬虫,Python都能胜任。这套Python基础教程不是教科书,不会玩弄概念,而是力求口语化和通俗化,让读者尽快入门。如果有小朋友出于兴趣学习Python,请引导他阅读本教程的前半部分,这是基础,可以降低学习成本;... 阅读详情

相关推荐

手把手教你打造CTF动态靶场

公司想搞一个CTF比赛,需要一个竞赛靶场,于是这个任务就落在了我的身上,平台是利用CTFd框架,基于docker搭建的动态靶场,搭建过程中遇到的坑比较多,这里我会把每一个遇到的坑都指出来。我搭建的是CTFd的3.X的版本。第一次搭建的话,搭建的过程会有些痛苦,但是搭建完成后会越来越熟练,这个平台的可用性还是很高的。由于搭建的过程中遇到的坑太多了,各种各样的问题,所以决定写下这篇文章,把所有的坑都指出来,也算为后边想搭这个平台的小伙伴指一条路。Taps:资源来源:星海安全实验室如果你也对网络安全&黑客。

Python栈 4931

[CLRS] Problems 16-1: Coin changing

link http://ripcrixalis.blog.com/2011/02/08/clrs-chapter-16/ Problems 16-1: Coin changing Consider the problem of making change for n cents using the fewest number of coins. Assume that each c

厚积薄发 4120

【深度学习3】ubuntu22.04从零开始搭建深度学习环境

ubuntu22.04从零开始搭建深度学习开发环境

weixin_43387635的博客 1万+

题解:The Fewest Coins(多重背包+完全背包)

Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods in such a way that the smallest number of coins changes hands, i.e., the number of coin...

晚安( ̄o ̄) . z Z 493

别再用Excel硬算传热了!用MATLAB/Octave复现国赛数学建模A题(附完整代码与避坑指南)

本文详细介绍了如何利用MATLAB/Octave高效解决数学建模中的传热问题,替代传统的Excel计算方法。通过复现2018年国赛A题的高温作业服传热模型,从理论推导到代码实现,提供了完整的有限差分法解决方案和参数拟合技巧,帮助读者提升数学建模效率和准确性。

weixin_30512965的博客 378

Simulink单相桥式有源逆变电路仿真:从器件选型到波形分析(MATLAB 2018a实战)

本文基于MATLAB 2018a的Simulink平台,详细演示了单相桥式有源逆变电路的完整仿真流程。从Simscape/Power Systems库的器件选型、参数配置,到触发脉冲设置与电路连接,逐步指导搭建仿真模型。通过调整触发角α,直观展示了电路从整流到有源逆变的工作状态切换,并深入分析了负载电压、电流波形,以及逆变颠覆现象的产生条件与特征。

cake8的博客 1159

uva 166 Making Change

博主有一个通熟易懂的方法解这道题,希望大家喜欢,背包简化,不用数组标记也可以做#include #include #include #include using namespace std; int coin[6] = {1,2,4,10,20,40}; int num[6]; int store(int n) { int ans = 0; for(int i = 5;

论菜鸟的自我修养。。。 736

linux操作系统使用以太网连接ubuntu,设置固定ipv4

首先,您需要确定要配置的网络接口。可以使用ifconfig -a或ip addr命令来列出当前系统上的所有网络接口及其相关信息。找到您要配置的网络接口名称,例如eth0、ens33或enp0s3;保存并关闭文件后,您需要重启网络服务以使更改生效。在linux操作系统中,要使用交换机连接以太网可以直接使用交互界面;如果你的操作系统没有交互界面,你可以使用命令方式配置;点击ipv4,方式为手动,可以设置ip和子网了;开头,后接网络接口名称。第三步:点击有线最右边圆形控件;第二步:点击有线设置;

2301_79311842的博客 2404

coin change problem 的一个变体

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t mat

a130737的专栏 984

YOLOv11改进策略【卷积层】| DEConv: 强度信息与梯度特征融合的细节增强 适用于小目标与细节目标检测任务

本文记录的是利用 模块优化 的目标检测网络模型。(Detail-Enhanced Convolution,细节增强卷积)的设计旨在,解决 目标检测网络中传统普通卷积缺乏目标细节相关先验、对小目标边缘、目标与背景边界等关键细节捕捉能力不足的问题,同时避免引入额外参数量与计算开销,以适配 对实时推理性能与检测精度的双重需求。DEA-Net: Single image dehazing based on detail-enhanced convolution and content-guided atte

Limiiiing的博客 1496

【四足机器人项目实战】四足机器人腿部机械结构设计

系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 TODO:写完再整理 文章目录系列文章目录前言 前言 认知有限,望大家多多包涵,有什么问题也希望能够与大家多交流,共同成长! 本文先对四足机器人–腿部机械结构设计做个简单的介绍,具体内容后续再更,其他模块可以参考去我其他文章 提示:以下是本篇文章正文内容 为了减轻腿部惯量,使用有限元分析着重进行轻量化设计,小腿采用工字梁方案,大腿采用内部镂方案,并使用1.5 mm的AL 6061硬质材料,轻量化的腿部设了腿部运动时摆动

qq_35635374的博客 7538

Google - Find minimum number of coins that make a given value

Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change? Examples:...

weixin_33670713的博客 185

小波变换完全指南:从原理到实践的深度解析

在信号处理领域,傅里叶变换长期以来一直是频域分析的主要工具。然而,傅里叶变换存在一个根本性的局限:它只能告诉我们信号中包含哪些频率成分,却无法告诉我们这些频率成分在什么时刻出现。这就像是你知道一首歌用了哪些音符,却不知道这些音符的演奏顺序。小波变换(Wavelet Transform) 应运而生,它完美地解决了这个问题。小波变换不仅能够提供频率信息,还能同时提供时间信息,实现了信号的时频联合分析。本文将带你从零开始,深入理解小波变换的原理、实现和应用。傅里叶变换的定义如下: 它使用正弦和余弦这样的全局基函数

电脑管家 207

Make Cents

Every year, an elephant qualifies to the Arab Collegiate Programming Competition. He graduated this year, but that’s irrelephant. What’s important is that the location of the competition might no...

weixin_30357231的博客 139

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Coin Change

You are given coins of different denominations and a total amount of moneyamount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money ...

leetcode 解题思路 484

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

c#学习心得【1】【基础语法部分1】

C#的学习心得

LEOZHANG的专栏 645

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

跑酷解析_0

using UnityEngine; using System.Collections; using System.Collections.Generic; // class that animates the coin moving from the player to the coin indicator on the GUI public class CoinGUICollection :

萌哒哒~ 469

DP 换硬币问题

设有n种不同面值的硬币,现要用这些面值的硬币来找开待凑钱数m,可以使用的各种面值的硬币个数不限。    找出最少需要的硬币个数,并输出其币值。 package DP; import java.util.Arrays; /** * A country has coins with denominations * 1 = d1 < d2 < · · · < dk

3268

判断是否字符串重组 Scramble String @LeetCode

思路: 1 递归: 简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22。 那么要么s11和s21是scramble的并且s12和s22是scramble的; 要么s11和s22是scramble的并且s12和s21是scramble的。 如果要能通过OJ,还必须把字符串排序后进行剪枝 http://

1万+

深入理解递归

大家都知道,递归的本质和栈数据的存取很相似了,都是先进去,但是往往最后处理!再者对于递归函数的局部变量的存储是按照栈的方式去存的,对于每一层的递归函数在栈中都保存了本层函数的局部变量,一边该层递归函数结束时能够保存原来该层的数据!如图:               如上图递归式依次往下进行的,并且在该层递归函数还没结束即将进入下一层递归调用时,将会把该层函数中的局部变量保存起来,以供下次使用!

7758

Edit Distance 编辑距离算法 @LeetCode

又是一道典型DP! 我们将人生划为诡异的阶段 我们把这个世界表为丰富的状态 package DP; import java.util.Arrays; /** * Edit Distance * * Given two words word1 and word2, find the minimum number of steps required to conve

5661

DP30 求骰子能凑成给定和的组合数 Dice Throw @geeksforgeeks

Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown. The Naive approach is to find all

4570

总结帖:全排列Permutation,子集subset 递归模板

两个经典递归模板,以前写过,现在再过一遍! 基本思路: 如果题目给的输入时数组,首先先要把数组转为ArrayList,因为ArrayList可以很方便地插入,删除,添加! 其次,递归函数的形式都一样,一共有3个参数,分别叫ArrayList done, ArrayList rest, ArrayList> ret 。 done存放已经处理过的数据,rest存放还没处理的数据,ret存

3714

DP22 堆盒子问题 Box Stacking Problem @geeksforgeeks

You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possi

3480

DP34 流水线调度问题 Assembly Line Scheduling @geeksforgeeks

A car factory has two assembly lines, each with n stations. A station is denoted by Si,j where i is either 1 or 2 and indicates the assembly line the station is on, and j indicates the number of the s

3373
上一篇: 老鸟的Python入门教程
下一篇: DP8 矩阵链相乘 Matrix Chain Multiplication @geeksforgeeks
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值