Press "Enter" to skip to content

花花酱 LeetCode 518. Coin Change 2

题目大意:给你一些硬币的面值,问使用这些硬币(无限多块)能够组成amount的方法有多少种。

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.

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

Example 1:

Example 2:

Example 3:

Idea: DP

Transition 1:

Let us use dp[i][j] to denote the number of ways to sum up to amount j using first i kind of coins.

dp[i][j] = dp[i – 1][j – coin] + dp[i – 1][j – 2* coin] + …

Time complexity: O(n*amount^2) TLE

Space complexity: O(n*amount) -> O(amount)

Transition 2:

Let us use dp[i] to denote the number of ways to sum up to amount i.

dp[i + coin] += dp[i]

Time complexity: O(n*amount)

Space complexity:  O(amount)

C++

Java

Python

 

Related Problems:

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply