bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

3. Coin Change #3

Open bonfy opened 5 years ago

bonfy commented 5 years ago

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.

Leetcode: Coin Change - https://leetcode.com/problems/coin-change/

bonfy commented 5 years ago

解法1: DP

时间复杂度 O(amount * len(coins))

Bottom UP

For example: Input: coins = [1, 2, 5], amount = 11 DP[0] = 0 DP[1] = 1 DP[2] = 1 DP[3] =min(DP[2] + DP[1], DP[1]+DP[1]+DP[1]) = 2

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [0] + [amount+1] * amount
        coins.sort()
        for coin in coins:
            for i in range(coin, amount+1):
                dp[i] = min(dp[i], dp[i-coin]+1)
        return dp[-1] if dp[-1] != amount+1 else -1
bonfy commented 5 years ago

进阶:

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

Leetcode: Coin Change 2 - https://leetcode.com/problems/coin-change-2/

bonfy commented 5 years ago

解法:DP

class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        dp = [0]*(amount + 1)
        dp[0] = 1

        for coin in coins:
            for i in range(coin, amount + 1):
                dp[i] += dp[i - coin]

        return dp[-1]