动态规划 139 Word Break + 322 Coin Change

本文解析了两个典型的动态规划问题:硬币找零问题及单词拆分问题。通过实例展示了如何利用动态规划解决最少硬币找零数目及检查字符串是否能由字典中的单词完全匹配组成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态规划总结

322. Coin Change

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.


解答:

class Solution(object):
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        amount_list = [0] + [-1] * amount #创建一个1+amount长度的列表,第一个表示值为0的“coin”
        for i in xrange(1, amount + 1):
            if i in coins:                #如果当前值在coin中有则直接设为1
                amount_list[i] = 1
            for j in coins:
                if j < i and amount_list[i-j] != -1:
                    if amount_list[i] == -1 or amount_list[i] > 1 + amount_list[i-j]:
                        amount_list[i] = 1 + amount_list[i-j]
        return amount_list[-1]

判断从1开始的每一个数分别需要对应于多少个coin的数量;
如果减去正在考察的coin的量后,能够对应于一个非负的数字(说明减去后的这个数能用coin表示),那就加上正在考察的coin这个“1”个;
最后一个数便是所求答案。


139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because “leetcode” can be segmented as “leet code”.


解答:

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        length_s = len(s)
        d = [False] * length_s
        for i in xrange(length_s):
            for w in wordDict:
                if w == s[i-len(w)+1:i+1] and (d[i-len(w)] or i-len(w) == -1 ):
                    d[i] = True
        return d[-1]

本题需要完美分割,也就是不剩下任何一个字符,和上一题一样,看当前字符的len(word)前的那一个字符能不能在wordList中找到或者是不是s字符串的首位。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值