- 浏览: 172998 次
- 性别:
- 来自: 济南
文章分类
最新评论
Coin Change
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
题目的意思是给定一些不同面值的硬币和一个数值,写一个方法来判断是否能用现有的硬币组成给定的数值。假设每个面值的硬币都有无限个,如果可以组成给定的数值,就返回最少硬币的个数,否则返回-1。
这道题属于动态规划的问题,如果不用动态规划在leetcode上也可以ac,但是速度比较慢。用哈希表记录一个差值,就是给定的数值amount > coins[i]时,每遍历完一遍都更新哈希表,知道找到结果。代码如下:
接下来我们动态规划的方法做,我们用一个数组dp[]来表示从0到amount,如果coins[i] = x时,x属于0到amount,dp[x] = 1; 当 x > coins[i]时,我们要查看之前是否已经计算出总数为x-coins[i]的情况,如果已经计算出,dp[x] = Math.min(dp[i - coins[j]] + 1, dp[x]);如果没有计算出就继续查找。细节的地方需要注意,比如数组的初始化等,代码如下:
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
题目的意思是给定一些不同面值的硬币和一个数值,写一个方法来判断是否能用现有的硬币组成给定的数值。假设每个面值的硬币都有无限个,如果可以组成给定的数值,就返回最少硬币的个数,否则返回-1。
这道题属于动态规划的问题,如果不用动态规划在leetcode上也可以ac,但是速度比较慢。用哈希表记录一个差值,就是给定的数值amount > coins[i]时,每遍历完一遍都更新哈希表,知道找到结果。代码如下:
public class Solution { public int coinChange(int[] coins, int amount) { if(amount == 0) return 0; Arrays.sort(coins); int result = 1; HashSet<Integer> helper = new HashSet<Integer>(); for(int i = 0; i < coins.length; i++) { if(coins[i] == amount) { return result; } else if(amount > coins[i]) { helper.add(amount - coins[i]); } } boolean flag = true; while(flag) { HashSet<Integer> newset = new HashSet<Integer>(); result ++; for(int newAmount : helper) for(int coin : coins) { if(newAmount == coin) { return result; } else if(newAmount > coin) { if(newAmount - coin >= coins[0]) { newset.add(newAmount - coin); } } else { break; } } if(newset.isEmpty()) { flag = false; } else { helper = newset; } } return -1; } }
接下来我们动态规划的方法做,我们用一个数组dp[]来表示从0到amount,如果coins[i] = x时,x属于0到amount,dp[x] = 1; 当 x > coins[i]时,我们要查看之前是否已经计算出总数为x-coins[i]的情况,如果已经计算出,dp[x] = Math.min(dp[i - coins[j]] + 1, dp[x]);如果没有计算出就继续查找。细节的地方需要注意,比如数组的初始化等,代码如下:
public class Solution { public int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; for(int i = 1; i < dp.length; i++) dp[i] = Integer.MAX_VALUE; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < coins.length; j++) { if(i - coins[j] == 0) { dp[i] = 1; break; } else if(i - coins[j] > 0) { int val = dp[i - coins[j]]; if(val != Integer.MAX_VALUE) { dp[i] = Math.min(dp[i], val + 1); } } } } return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount]; } }
发表评论
-
498. Diagonal Traverse
2019-11-15 13:52 224Given a matrix of M x N eleme ... -
496 Next Greater Element I
2019-11-14 13:50 222You are given two arrays (witho ... -
Word Break II
2016-03-09 03:15 338Given a string s and a dictiona ... -
Insert Interval
2016-03-08 02:11 330Given a set of non-overlapping ... -
Merge Intervals
2016-03-07 05:25 448Given a collection of intervals ... -
Merge k Sorted Lists
2016-03-07 04:03 508Merge k sorted linked lists and ... -
Multiply Strings
2016-03-06 07:27 427Given two numbers represented a ... -
N-Queens II
2016-03-06 03:06 617Follow up for N-Queens problem. ... -
N-Queens
2016-03-06 02:47 425The n-queens puzzle is the prob ... -
First Missing Positive
2016-03-05 03:09 383Given an unsorted integer array ... -
Spiral Matrix
2016-03-04 03:39 514Given a matrix of m x n element ... -
Trapping Rain Water
2016-03-04 02:54 528Given n non-negative integers r ... -
Repeated DNA Sequences
2016-03-03 03:10 366All DNA is composed of a series ... -
Increasing Triplet Subsequence
2016-03-02 02:48 858Given an unsorted array return ... -
Maximum Product of Word Lengths
2016-03-02 01:56 878Given a string array words, fin ... -
LRU Cache
2016-02-29 10:37 552Design and implement a data str ... -
Super Ugly Number
2016-02-29 07:07 597Write a program to find the nth ... -
Longest Increasing Path in a Matrix
2016-02-29 05:56 760Given an integer matrix, find t ... -
Coin Change
2016-02-29 04:39 731You are given coins of differen ... -
Minimum Height Trees
2016-02-29 04:11 626For a undirected graph with tre ...
相关推荐
Coin Change問題 計算錢幣兌換問題 有幾種可能
Dynamic Programming Solution to the Coin Changing Problem
这是来自LeetCode的已解决任务的存储库使用Java语言解决任务 CoinChange.java - //leetcode....
LeetCode-Coin-Change
技术面试 ...│ │ ├── CoinChange.java │ │ └── WildcardPatternMatching.java │ ├── HashTables │ │ ├── CompoundWord.java │ │ └── RansomNote.java │ ├─
解决HackerRank练习挑战的方法 音轨 演算法 暖身 挑战 解决方案 时间复杂度 空间复杂度 O(1) O(1) 上) O(1) O(1) O(1) 上) O(1) 上) O(1) 正负 Java 上) O(1) ... 女王的进攻
Change) Tip4: backtrace or K sum remove duplicates if i != 0 and n == nums[i-1]: (#15. 3Sum) if idx > start and nums[idx] == nums[idx-1]: continue (#40. Combination Sum II) Tip5: 鸽笼原理要记得,如果...
Change JS (组合,动态自下而上) 组字谜JS 水容器JS 第一个缺失的正JS 水果入篮JS CodeSignal 街机问题 介绍 10 - 常见字符计数JS & Python 13 - 在括号中反转JS & Python 14 - 交替求和JS & Python 15 - 添加边框...
CoinChange(#322), EditDistance(#72) 图 : 集合的合并(直接求并、按大小求并和按深度求并)、根搜寻(路径压缩) : 有向图和无向图的邻接表表示方法 : 图的深度优先和广度优先搜索(假设图用邻接表矩阵表示)、拓扑...
leetcode 和 oj 简介 :balloon: 题目为九章算法DP专题中讲到的...coinChange(vector<int>& coins, int amount) { sort(coins.begin(),coins.end()); //不得不忍受一个排序的时间复杂度 if(amount == 0) { return 0; }
CoinChange DFS(Deep First Search)深度优先搜索 岛屿的最大面积(MaxAreaOfIsland) BFS(Breath First Search)广度优先搜索 图论 最短路径 最小生成树 动态规划(dp) 最长上升子序列(lengthOfLIS) 基础技巧 ...
lru cache leetcode LeetCode 个人练习 struct algorithm 目录分为 2 个目录,分别是数据结构和算法 数据结构 存放一些底层语言需要实现的基本数据结构,算法可能会用得上的 ...coinChange subdomainVisits
算法问题解决 用于准备编程比赛的算法和数据结构(例如ACM-ICPC,)和编码采访。 克里斯托弗·杜尔(ChristophDürr)和吉尔·詹恩·维(Jill...print ( coin_change ([ 3 , 5 , 11 ], 29 )) # True because 29 = 6 x 3
动态编程递归无重复每个子问题只能评估一次天真的递归方法由于重复而花费指数时间自上而下的回忆这是递归的深度优先搜索实现缓存重复工作自下而上基于依赖图将递归转换为依赖图它是有向无环图您可以使用拓扑排序对......
coin-change-ii-0518 组合和-iv-0377 解码方式-0091 盗家贼-0198 盗家贼-ii-0213 jump-game-0055 最长公共子序列1143 最长公共子串 最长递增子序列0300 最大积子阵列0152 最大子阵列-0053 唯一路径-0062 word-break-...
捡起/投币(PickUp/Coin) 激光/射击(Laser/Shoot) 爆炸(Explosion) 能量升级(PowerUp) 击中/受伤(Hit/Hurt) 弹开/选择(Blip/Select) 突变(mutate,生成当前音效的相似效果) 随机化(Randomizc)...
coins needed to make change for a given amount, we can repeatedly select the largest-denomination coin that is not larger than the amount that remains. A greedy approach provides an optimal solution ...
长期 京豆变动通知 jd_bean_change.js 长期 领京豆额外奖励&抢京豆 jd_bean_home.js 长期 京东多合一签到 jd_bean_sign.js 长期 东东超市兑换奖品 jd_blueCoin.js 长期 口袋书店 jd_bookshop.js 长期 京东汽车赛点...
freeCodeCamp-算法和数据结构项目5-收银机设计一个收银机抽屉函数checkCashRegister(),该函数将购买价格作为第一个参数(价格),将... 返回{ status : "INSUFFICIENT_FUNDS" , change : [ ]} 如果抽屉中的现金少于
Solver pulp.solvers.COIN_CMD unavailable Solver pulp.solvers.COINMP_DLL unavailable Testing zero subtraction Testing inconsistant lp solution Testing continuous LP solution Testing maximize ...