// solve 5 : dfs + greedy + pruning var coinChange = function(coins,amount){ var res = Infinity coins.sort((a,b)=>b-a) change(amount,0,0) return res === Infinity?-1:res // 内部调用函数类 function change(amount,count,cidx){ // base case if(amount === 0){ res = Math.mi...
可以直接运行的代码 leetcode的testcase有一个为amount为0的时候,所以在代码的开头加了一个判断。 吐槽一下leetcode怎么有这么多诡异的testcase。 classSolution:defcoinChange(self,coins:List[int],amount:int)->int:ifamount==0:return0dp=[amount+1]*(amount+1)dp[0]=0foriinrange(1,amount+1):forcin...
本题不能用greedy algorithm。因为硬币的组合可能不是greedy basis。离散的问题求极值一般还是使用DP。 1classSolution(object):2def coinChange(self, coins, amount):3"""4:type coins: List[int]5:type amount:int6:rtype:int7"""8int_max =21474836479dp = [0]+[int_max]*amount1011foriinrange(amou...
Youtube B站 Thought Process This is a classic problem and greedy might be the first thing comes into mind. For example, sort the coins on denomination and always use the largest amount coin. However, the optimal solution might not include the largest denomination. for example , [1, 3, 4]...
刚开始想的是能不能像 【DP、Greedy】416. Partition Equal Subset Sum 这道题那样,硬币从大到小排序,然后使用贪心算法来求解。但是如果几个例子,比如 coins = [4,3],,amount = 14,如果使用贪心,会找到 4 4 4,然后发现到不了 14,返回 -1。实际上,应该是 4 4 3 3,返回 4。因此,贪心的思想行不通...
解法二:Greedy+DFS+Pruning (贪心算法+递归深度优先搜索+剪枝) 方针:将coins从大到小排序,每次尝试最大的面值,若总价刚好能够被coin整除,则将所用硬币个数->res 否则,从该面值的最大个数amount/coin开始依次递减,尝试: 剩下的余额amount-amount/coin*coin,用下一个小的面值硬币,需要的硬币个数。
If coin order matters, that is, each sequence is unique, the DP function is simple enough to make it 1D DP. But key is that order DOESN'T matter, so we need to add one more state: ending coin. And for each DP advance step, we only put >= coins. ...