LeetCode-322. Coin Change

网友投稿 763 2022-08-25

LeetCode-322. Coin Change

LeetCode-322. 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​​.

Example 1:

Input: coins = ​​[1, 2, 5]​​​, amount = ​​11​​ Output: ​​3​​ Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = ​​[2]​​​, amount = ​​3​​ Output: -1

Note: You may assume that you have an infinite number of each kind of coin.

题解:

第一想法就是dp,判断coins组成1-amount的最少硬币数,然后返回dp[n - 1][amount];

class Solution {public: int coinChange(vector& coins, int amount) { int n = coins.size(); vector> dp(amount + 1, vector(n, amount + 1)); dp[0][0] = 0; for (int i = 0; i < n; i++) { dp[0][i] = 0; } for (int i = 1; i <= amount; i++) { for (int j = 0; j < n; j++) { if (j > 0) { dp[i][j] = dp[i][j - 1]; } if (i - coins[j] >= 0) { dp[i][j] = min(dp[i][j], dp[i - coins[j]][j] + 1); } } } if (dp[amount][n - 1] == amount + 1) { return -1; } return dp[amount][n - 1]; }};

发现每次dp[i][j]只用到了dp[i][j - 1]这个值,可以不存储coins这个维度。

class Solution {public: int coinChange(vector& coins, int amount) { int n = coins.size(); vector dp(amount + 1, amount + 1); dp[0] = 0; for (int i = 1; i <= amount; i++) { for (int j = 0; j < n; j++) { if (i - coins[j] >= 0) { dp[i] = min(dp[i], dp[i - coins[j]] + 1); } } } if (dp[amount] == amount + 1) { return -1; } return dp[amount]; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:golang共识锁实现用户地址分配
下一篇:有限域上的逆元求解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~