Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Coin Change

$
0
0

题目描述:

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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

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

题目大意:

给定不同面值的硬币和金额总值。编写函数计算凑齐金额总值最少需要的硬币数目。如果不可能凑齐指定的金额,返回-1。

测试用例如题目描述。

注意:

你可以假设每种面值的硬币数目都是无穷的。

解题思路:

动态规划(Dynamic Programming)

状态转移方程:

dp[x + c] = min(dp[x] + 1, dp[x + c])

其中dp[x]代表凑齐金额x所需的最少硬币数,c为可用的硬币面值

初始令dp[0] = 0

贪心算法是不正确的,因为有可能会错过全局最优解。

Python代码:

class Solution(object):
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        dp = [-1] * (amount + 1)
        dp[0] = 0
        for x in range(amount):
            for c in coins:
                if x + c > amount or dp[x] < 0:
                    continue
                if dp[x + c] < 0 or dp[x + c] > dp[x] + 1:
                    dp[x + c] = dp[x] + 1
        return dp[amount]

 


Viewing all articles
Browse latest Browse all 559

Trending Articles