1. Word Break

  题目链接

  题目要求:

  Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

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

  Return true because "leetcode" can be segmented as "leet code".

  博文Word Break -- LeetCode提及了动态规划的思想:

  首先我们要决定要存储什么历史信息以及用什么数据结构来存储信息。然后是最重要的递推式,就是如从存储的历史信息中得到当前步的结果。最后我们需要考虑的就是起始条件的值。

  下边是该博文对该题目的分析:

  首先我们要存储的历史信息res[i]是表示到字符串s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。然后假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的表达式。思路是对于每个以i为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的res[j]是不是true,如果都成立,那么res[i]为true,写成式子是

  

  具体程序如下:

 class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int szS = s.size();
if(szS == )
return false; vector<bool> dp(szS + , false);
dp[] = true;
for(int i = ; i < szS + ; i++)
{
for(int j = i - ; j > -; j--)
{
if(dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end())
{
dp[i] = true;
break;
}
}
} return dp[szS];
}
};

  2. Word Break II

  题目链接

  题目要求:

  Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

  Return all such possible sentences.

  For example, given
  s = "catsanddog",
  dict = ["cat", "cats", "and", "sand", "dog"].

  A solution is ["cats and dog", "cat sand dog"].

  其实这道题比上一道题理解来得容易,直接用Brute Force或者想直接利用上一题的结果来得到最终结果,都会超时。具体的,就是对输入进行检查,看看输入是否可以分解的,这样就可以跟超时了。

  Brute Force程序:

 class Solution {
public:
bool isValid(string s, unordered_set<string>& wordDict)
{
return wordDict.find(s) != wordDict.end();
} void dfs(string s, string tmp, vector<string>& res, unordered_set<string>& wordDict)
{
if (s.size() == )
{
tmp.pop_back(); // delete blank space
res.push_back(tmp);
return;
} int sz = s.size();
for(int i = ; i < sz + ; i++)
{
string str = s.substr(, i);
if(isValid(str, wordDict))
dfs(s.substr(i), tmp + str + " ", res, wordDict);
}
} vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<string> res;
int szS = s.size();
if(szS == )
return res; vector<bool> dp(szS + , false);
dp[] = true;
for(int i = ; i < szS + ; i++)
{
for(int j = i - ; j > -; j--)
{
if(dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end())
{
dp[i] = true;
break;
}
}
} if(dp[szS])
dfs(s, "", res, wordDict); return res;
}
};

  利用上一题的结果:

 class Solution {
public:
bool isValid(string s, unordered_set<string>& wordDict)
{
return wordDict.find(s) != wordDict.end();
} void dfs(string s, string tmp, vector<string>& res, vector<int> inDictPos, unordered_set<string>& wordDict)
{
if (s.size() == )
{
tmp.pop_back(); // delete blank space
res.push_back(tmp);
return;
}
int sz = inDictPos.size();
if (sz > )
{
for (int i = ; i < sz; i++)
{
int diff = inDictPos[i] - inDictPos[];
if (diff <= s.size())
{
string subStr = s.substr(, diff);
if (isValid(subStr, wordDict))
{
vector<int> _inDictPos(inDictPos);
_inDictPos.erase(_inDictPos.begin(), _inDictPos.begin() + i);
string tmpStr = s.substr(diff);
dfs(s.substr(diff), tmp + subStr + " ", res, _inDictPos, wordDict);
}
}
}
}
} vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
// Implemented in Word Break I
int szS = s.size();
vector<bool> dp(szS + , false);
vector<int> inDictPos;
dp[] = true;
inDictPos.push_back();
for(int i = ; i < szS + ; i++)
{
for(int j = i - ; j > -; j--)
{
if(dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end())
{
dp[i] = true;
inDictPos.push_back(i);
break;
}
}
} vector<string> res;
if(dp[szS])
dfs(s, "", res, inDictPos, wordDict); return res;
}
};

  相比较之下,当然只用BF就够了,而且还来得简单。

LeetCode之“动态规划”:Word Break && Word Break II的更多相关文章

  1. leetcode 140 单词拆分2 word break II

    单词拆分2,递归+dp, 需要使用递归,同时使用记忆化搜索保存下来结果,c++代码如下 class Solution { public: //定义一个子串和子串拆分(如果有的话)的映射 unorder ...

  2. leetcode@ [211] Add and Search Word - Data structure design

    https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...

  3. (*medium)LeetCode 211.Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  4. LeetCode 5:Given an input string, reverse the string word by word.

    problem: Given an input string, reverse the string word by word. For example: Given s = "the sk ...

  5. Java for LeetCode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...

  6. [LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  7. Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II)

    Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II) 编写一个程序,找出第 n 个丑数. 丑数就是只包含质因数 2, 3, 5 的正整数. 示例: 输入: n ...

  8. Leetcode之动态规划(DP)专题-122. 买卖股票的最佳时机 II(Best Time to Buy and Sell Stock II)

    Leetcode之动态规划(DP)专题-122. 买卖股票的最佳时机 II(Best Time to Buy and Sell Stock II) 股票问题: 121. 买卖股票的最佳时机 122. ...

  9. Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II)

    Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II) 初级题目:Leetcode之动态规划(DP)专题-62. 不同路径(Unique Paths) 一个机 ...

  10. 【LeetCode】819. Most Common Word 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 正则+统计 日期 题目地址:https://leet ...

随机推荐

  1. CSS简单使用

    CSS简单使用 标签 : 前端技术 CSS(Cascading Style Sheet : 层叠样式表单)用来定义网页显示效果. 可以解决HTML代码对样式定义的重复,提高后期样式代码的可维护性,并增 ...

  2. activiti 动态配置 activiti 监听引擎启动和初始化(高级源码篇)

    1.1.1. 前言 用户故事:现在有这样一个需求,第一个需求:公司的开发环境,测试环境以及线上环境,我们使用的数据库是不一样的,我们必须能够任意的切换数据库进行测试和发布,对数据库连接字符串我们需要加 ...

  3. SpriteKit中的共享动作(Sharing Actions)

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 在SpriteKit中某些动作需要一些额外的延时,如果每次都重 ...

  4. SQLite 附加数据库(http://www.w3cschool.cc/sqlite/sqlite-attach-database.html)

    SQLite 附加数据库 假设这样一种情况,当在同一时间有多个数据库可用,您想使用其中的任何一个.SQLite 的 ATTACH DTABASE 语句是用来选择一个特定的数据库,使用该命令后,所有的 ...

  5. Java并发框架——AQS之原子性如何保证?

    在研究AQS框架时,会发现这个类很多地方都使用了CAS操作,在并发实现中CAS操作必须具备原子性,而且是硬件级别的原子性,java被隔离在硬件之上,明显力不从心,这时为了能直接操作操作系统层面,肯定要 ...

  6. Android简易实战教程--第二十一话《内容观察者监听数据库变化》

    当数据库的数据发生改变,我们又想知道具体改变的情况时,就需要对数据库的变化情况做一个监控.这个任务,就由内容观察者来完成.下面这个案例,为短信数据库注册内容观察者,来监控短信的变化情况,当短信数据库发 ...

  7. 【一天一道LeetCode】#374. Guess Number Higher or Lower

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 We are ...

  8. Android开发工具下载地址

    Android Studio: http://zdz.la/iq4zSa

  9. 学习笔记-JS公开课一

    JS公开课笔记 没特别说明就是和Java语言一样. JS变量:弱类型语言 1.在JS中,true表示1,false表示0.和Java不一样. 2. var y: 提示undefined: 3.如果al ...

  10. 【嵌入式开发】 嵌入式开发工具简介 (裸板调试示例 | 交叉工具链 | Makefile | 链接器脚本 | eclipse JLink 调试环境)

    作者 : 韩曙亮 博客地址 : http://blog.csdn.net/shulianghan/article/details/42239705  参考博客 : [嵌入式开发]嵌入式 开发环境 (远 ...