找零钱
来源:互联网 发布:液晶电视编程器 编辑:程序博客网 时间:2024/04/29 11:14
通过计算所有从0到maxChange地最佳找零,并保存信息用来构造实际的硬币序列以解决找零问题的动态规划算法
package com.dynamic.cc;/*** * * @author SunnyBoy * */public class GiveChange { public static void main(String[] args) { int[] coins = { 1, 2, 5, 10, 20, 50, 100 }; int differentCoins = 7; int maxChange = 3; int[] coinsUsed = new int[maxChange + 1]; int[] lastCoin = new int[maxChange + 1]; makeChange(coins, differentCoins, maxChange, coinsUsed, lastCoin); for (int i = 1; i < lastCoin.length; i++) { System.out.println(i + ":" + coinsUsed[i]); } }/*** * Dynamic programming algorithm to solve change-making problem. * 从开始逐渐的构造数组coinsUsed寻找实际要求的找零钱的最佳找零 * @param coins * @param differentCoins * @param maxChange * @param coinsUsed * @param lastCoin */ private static void makeChange(int[] coins, int differentCoins, int maxChange, int[] coinsUsed, int[] lastCoin) { coinsUsed[0] = 0; lastCoin[0] = 1; for (int cents = 1; cents <= maxChange; cents++) { int minCoins = cents; int newCoin = 1; for (int j = 0; j < differentCoins; j++) { if (coins[j] > cents) continue; if (coinsUsed[cents - coins[j]] + 1 < minCoins) { minCoins = coinsUsed[cents - coins[j]] + 1; newCoin = coins[j]; } } coinsUsed[cents] = minCoins; lastCoin[cents] = newCoin; } }}
阅读全文
0 0
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱!
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 找零钱
- 动态归化 找零钱
- 找零钱问题
- 单一职责原则(Single Responsibility Principle)
- CCF 历年真题之消除类游戏(_1512_2_EliminationGame.java)参考答案
- 堆和栈的区别!
- 1016. 部分A+B (15)
- MyBatis 教程
- 找零钱
- PHP7在thinkphp5下连接mysql
- maven认识与快速入门
- Android版本和API Level对应关系
- Excel数据导入Sql Server出现Null
- 算法调整队形
- 属性, 变量,@property,@synthesize,@dynamic
- 7个值得了解的性能,错误监控工具/平台
- fabric源码解析3——日志系统