动态规划 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字符串的首位。
- 动态规划 139 Word Break + 322 Coin Change
- [动态规划]UVA674 - Coin Change
- '动态规划:word-break'
- 动态规划:word-break
- uva 674 - Coin Change(动态规划)
- UVa 674 - Coin Change 动态规划入门
- uva 674 - Coin Change 动态规划
- UVA - 674 - Coin Change(动态规划)
- uva 674 coin change 动态规划
- hdoj--2069--Coin Change(动态规划)
- 322. Coin Change 动态规划应用
- 动态规划——322. Coin Change
- 动态规划中级教程 322. Coin Change
- 动态规划解322. Coin Change
- [LeetCode] [动态规划] Word Break
- 【LeetCode】Word Break 动态规划
- 139. Word Break 动态规划
- uva 674 Coin Change (动态规划:记忆化搜索)
- shell脚本--字符串的截取【面试题】
- Ricoboard开发板上RTC模块简单分析和使用
- parrot linux 使用
- chrom浏览器下input标签当auto-complete的时候背景色变黄色同时icon图标消失的解决方案
- 虚函数/纯虚函数,以及构造函数不能是虚函数原因
- 动态规划 139 Word Break + 322 Coin Change
- Mybatis 源码解析 -插件模块-分页例子
- 字符IO&数据流IO&对象流IO
- 曼哈顿距离(Manhattan Distance )详解
- sum=4+44+444+4444
- 一个应用实例详解卡尔曼滤波及其算法实现
- css div子元素剧中
- vector
- struts2之文件上传