ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 518. Coin Change 2

2020-06-08 12:54:57  阅读:364  来源: 互联网

标签:coin 硬币 int coins 518 amount Coin LeetCode dp


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.

Example 1:

Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3:

Input: amount = 10, coins = [10] 
Output: 1 

Note:

You can assume that

  • 0 <= amount <= 5000
  • 1 <= coin <= 5000
  • the number of coins is less than 500
  • the answer is guaranteed to fit into signed 32-bit integer

零钱兑换II。题意是给你一些不同面值的硬币coins和一个amount,请你返回有多少种硬币组合可以满足amount。

思路依然是动态规划。dp[i]的定义是当amount = i的时候,到底有几种硬币组合。

以基本情况没有硬币开始组合数量。dp[0] = 1,然后其余等于 0。
遍历所有硬币面值

  • 对于每个硬币,我们将从金额 0 遍历到 amount:
  • 对于每个 x,计算组合数:dp[x] += dp[x - coin]。
  • 返回 dp[amount]

时间O(n^2)

空间O(n)

Java实现

 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 x = coin; x < amount + 1; x++) {
 7                 dp[x] += dp[x - coin];
 8             }
 9         }
10         return dp[amount];
11     }
12 }

 

相关题目

322. Coin Change

518. Coin Change 2

983. Minimum Cost For Tickets

LeetCode 题目总结

标签:coin,硬币,int,coins,518,amount,Coin,LeetCode,dp
来源: https://www.cnblogs.com/cnoodle/p/13065029.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有