同时还有一个细节:在设置f的长度的时候要设置成amount + 1,因为这里是1 indexed(index对应的即选择的amount,而不是amount - 1)。 解法1: 1#definevi vector<int>2classSolution {3public:4intcoinChange(vi& coins,intamount) {5vi f(amount, amount +1);
图片来自于https://leetcode-cn.com/problems/coin-change/solution/wan-quan-bei-bao-wen-ti-shou-hua-dp-table-by-shixu/ 值得一提的是, 以原问题 amount = 11, coins = [2,5,1] 为例子。 i=1代表的是只可以放 {coin = 2,count =1}下,可以放n个小于11的情况 ...
https://leetcode-cn.com/problems/coin-change 解题思路 动态规划,自底向上,太简单,不解释。 C++代码 classSolution{public:intcoinChange(vector<int>& coins,intamount){vector<int>dp(amount +1, amount +1); dp[0] =0;for(inti =1; i <= amount; i++) {for(autov : coins) {if(i >= v)...
322. Coin ChangeMedium Topics Companies You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made...
Leetcode 322. Coin Change 硬币找零问题 MaRin 菜鸡一只 给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。你可以认为每种硬币的数量是无限的。对应leetcode链接为: https:/...
coins =[1, 2, 5], amount =11 return3Example 2: coins =[2], amount =3 return-1. Note: You may assume that you have an infinite number of each kind of coin. 思路: c[i]表示数目为i时最少需要多少个硬币。 算法: public int coinChange(int[] coins, int amount) { ...
本⽂聊的是 LeetCode 第 518 题 Coin Change 2,题⽬如下: Leetcode算法题第518题 PS:⾄于 Coin Change 1,在我们前⽂ 动态规划套路详解 写过。 我们可以把这个问题转化为背包问题的描述形式: 有⼀个背包,最⼤容量为 amount ,有⼀系列物品 coins ,每个物品的重量为 coins[i] ,每个物品的数量...
ChangeDFS(vector<int> &coins,intamount, vector<int> &dp) {if(amount <0)return-1;if(dp[amount] != INT_MAX)returndp[amount];for(inti =0; i < coins.size(); ++i) {inttmp = coinChangeDFS(coins, amount -coins[i], dp);if(tmp >=0) dp[amount] = min(dp[amount], tmp +1);...
return -1 if dp[amount] == float('inf') else dp[amount] 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. C++代码如下: class Solution { public: int coinChange(vector<int>& coins, int amount) { const int N = coins.size(); ...
public int coinChange(int[] coins, int amount) { if(amount==0) return 0; Arrays.sort(coins); if(coins==null || coins.length==0 || amount < coins[0]) return -1; int[] result = new int[amount+1]; for(int i = coins[0] ; i<=amount; i++){ ...