动态规划 139 Word Break + 322 Coin Change

来源:互联网 发布:凤凰台直播软件 编辑:程序博客网 时间:2024/05/17 05:16

动态规划总结

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字符串的首位。

原创粉丝点击