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];
	}
	
}

cadence—virtuosoic617的使用技巧收集区 cadence使用 阅读详情

相关推荐

解锁 STP 与 SOLIDWORKS 转换密码:工具及迪威在线转换秘籍

STP 文件能够完整地记录 3D 模型的几何形状、尺寸、公差、材料属性等丰富信息,无论是简单的机械零件,还是复杂的装配体,都能精准呈现。而在线转换以迪威模型为例,凭借便捷性、高效性和安全性,为广大 3D 专业技术人员和学生党在无需安装额外软件的情况下,轻松实现格式转换提供了有力支持。在实际工作和学习中,可根据自身具体情况灵活选择合适的转换方式,以确保 3D 设计工作流程的顺畅进行,让创意在不同格式间自由流动并绽放光彩。在 3D 设计与建模的广袤世界里,不同格式文件间的转换常常是连接创意与实现的关键桥梁。

技术说明博主 3465

[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

厚积薄发 4124

AI Agent实战:WorkBuddy安装部署、任务执行与模型接入全教程

AI Agent是当前自动化办公与智能工作流的核心技术,它区别于传统问答式AI,能够理解目标、拆解任务并调用工具交付完整成果。其底层原理基于任务规划、工具调用与结果验证的循环机制,让机器从“提供建议”进化为“完成任务”。在工程实践中,合理配置模型服务(如接入DeepSeek)、设计标准化Skill(技能包)与自定义指令,可以显著提升Agent在报告生成、数据分析、竞品调研等场景中的稳定性与效率。WorkBuddy作为典型的任务式AI工作台,为运营、产品、开发等多角色提供了统一入口,覆盖安装部署、任务描述公式

weixin_26712075的博客 300

题解: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 495

SAP FIORI静态磁贴从零到一:配置实战与权限打通

本文详细介绍了SAP FIORI静态磁贴的配置流程与权限管理,从准备工作到后台配置、目标映射、前台组织及权限分配,提供了实战技巧与常见问题解决方案。重点解析了静态磁贴的创建、目标映射配置及权限打通等关键步骤,帮助用户快速掌握FIORI静态磁贴的配置方法。

weixin_29266647的博客 256

保姆级教程:用GROMACS的FEP方法计算小分子结合自由能(附完整mdp配置)

本文提供了一份详细的GROMACS自由能微扰(FEP)计算教程,涵盖从系统准备、参数配置到结果分析的全流程。通过具体案例演示如何计算小分子结合自由能,包括λ窗口设计、动力学参数优化及并行化执行技巧,帮助研究者克服FEP计算中的常见问题,获得可靠的自由能数据。

weixin_30598225的博客 356

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

【tips】在PyCharm中安装opencv图文版详细教程

pip如下图所示,左边的蓝色图标就是终端。点开终端后,键入命令,按下回车后就开始下载了。如果你更喜欢图形化操作,可以在 PyCharm 中直接安装:。点击右上角的 +按钮(添加包)。搜索或,点击。

zhousanguhe的博客 6750

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

感应电机无速度传感器FOC控制原理与Simulink仿真实践

无速度传感器FOC控制是电机驱动领域的重要技术,通过算法重构实现仅依赖电气参数的闭环控制。其核心原理基于电机数学模型,利用Clark/Park变换和滑模观测器估算转子位置和转速。这种技术在工业伺服系统中具有显著价值,能有效降低系统成本并提高可靠性。典型应用场景包括纺织机械、风机驱动等需要精确转速控制的设备。本文以感应电机为例,详细解析了无感FOC的Simulink实现方法,特别关注滑模观测器设计和双闭环控制策略,为工程师提供可直接复用的参数调优经验。

weixin_29189987的博客 266

51、基于深度卷积神经网络的自闭症分类研究

本研究提出了一种基于深度卷积神经网络的自闭症分类方法,通过融合VGGNet-19和ResNet-52模型的特征,并在决策层采用SVM分类器,实现了对自闭症谱系障碍(ASD)和典型发育(TD)个体的准确区分。研究使用ABIDE数据集,结合数据增强和特征拼接技术,取得了88.12%的分类准确率和0.88的ROC曲线下面积。结果表明,该方法在自闭症自动诊断中具有良好的性能,同时研究也探讨了其局限性,并展望了未来改进方向,如多模态数据融合、迁移学习和模型可解释性的提升。

grpc6streamer的博客 134

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

【知识分享】高速印刷电路板(PCB)寄生参数计算指南

对于高速PCB设计而言,寄生参数一直是令人讨厌的问题,它们会悄悄潜入PCB并在电路中造成严重的破坏,具体来说,它们是渗透到高速电路中的隐藏杂散电容器和电感器,包括由封装引线和长走线形成的电感器、PCB焊盘对金属平面形成的电容器、走线之间形成的电容器等等。

一只豌豆象的博客 1788

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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

跑酷解析_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 :

萌哒哒~ 471

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

DP 换硬币问题

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

3269

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

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

C#的学习心得

LEOZHANG的专栏 645

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

判断是否字符串重组 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万+

深入理解递归

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

7759

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

5666

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存

3715

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

3375
上一篇: 老鸟的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、付费专栏及课程。

余额充值