LeetCode : 518. Coin Change 2凑硬币

不念不忘少年蓝@ 2021-06-24 16:12 476阅读 0赞

试题

  1. You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
  2. Example 1:
  3. Input: amount = 5, coins = [1, 2, 5]
  4. Output: 4
  5. Explanation: there are four ways to make up the amount:
  6. 5=5
  7. 5=2+2+1
  8. 5=2+1+1+1
  9. 5=1+1+1+1+1
  10. Example 2:
  11. Input: amount = 3, coins = [2]
  12. Output: 0
  13. Explanation: the amount of 3 cannot be made up just with coins of 2.
  14. Example 3:
  15. Input: amount = 10, coins = [10]
  16. Output: 1
  17. Note:
  18. You can assume that
  19. 0 <= amount <= 5000
  20. 1 <= coin <= 5000
  21. the number of coins is less than 500
  22. the answer is guaranteed to fit into signed 32-bit integer

代码
这一题明显动归, 但是循环嵌套很有技巧。如果我们把amount放在外循环,就会出现重复统计的情况,而把coins放在外部循环就能很好避免这种情况。

  1. class Solution {
  2. public int change(int amount, int[] coins) {
  3. int[] dp = new int[amount+1];
  4. dp[0] = 1;
  5. for(int coin : coins) {
  6. for(int i = 1; i <= amount; i++) {
  7. if(i - coin >=0) {
  8. dp[i] += dp[i-coin];
  9. }
  10. }
  11. }
  12. return dp[amount];
  13. }
  14. }

发表评论

表情:
评论列表 (有 0 条评论,476人围观)

还没有评论,来说两句吧...

相关阅读