LeetCode之“动态规划”:Word Break && Word Break II
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的更多相关文章
- leetcode 140 单词拆分2 word break II
单词拆分2,递归+dp, 需要使用递归,同时使用记忆化搜索保存下来结果,c++代码如下 class Solution { public: //定义一个子串和子串拆分(如果有的话)的映射 unorder ...
- leetcode@ [211] Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...
- (*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 ...
- 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 ...
- 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 ...
- [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 ...
- Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II)
Leetcode之动态规划(DP)专题-264. 丑数 II(Ugly Number II) 编写一个程序,找出第 n 个丑数. 丑数就是只包含质因数 2, 3, 5 的正整数. 示例: 输入: n ...
- 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. ...
- Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II)
Leetcode之动态规划(DP)专题-63. 不同路径 II(Unique Paths II) 初级题目:Leetcode之动态规划(DP)专题-62. 不同路径(Unique Paths) 一个机 ...
- 【LeetCode】819. Most Common Word 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 正则+统计 日期 题目地址:https://leet ...
随机推荐
- [csdn markdown]使用摘记二 快捷键及导入导出Markdown文件
csdn推出了新的编辑器markdown,对于习惯使用离线编辑的人员来说是个大的福利,比如上班的时候,不能联网,但是又有好些知识点需要记录,等到下班了呢,又想直接把这些排版格式良好的文件直接上传到cs ...
- C++ 中const作用
一.对const与#define的特点及区别的理解 #define只是用来做文本替换的,#define常量的生命周期止于编译期,它存在于程序的代码段,在实际程序中它只是一个常数,一个命令中的参数,并没 ...
- Java基本语法-----java注释
1注释的作用 通过注释提高程序的可读性,是java程序的条理更加清晰,易于区分代码行与注释行.另外通常在程序开头加入作者,时间,版本,要实现的功能等内容注释,方便后来的维护以及程序员的交流. 2注释的 ...
- Android事件分发回传机制
转载本博客,请注明出处:点击打开链接 http://blog.csdn.net/qq_32059827/article/details/52489026 之前以一个爷爷给孙子分馒头的故事,初探了安 ...
- everything of people’s life can changed in their twenties
还记得三年前,独自背着行李,流浪远方,来到曾经只在地理课本上才熟悉的北国,带着好奇,带着期望,带着激动的心情,想感受毛爷爷当年霸气的北国风光,千里冰封的美丽,想知道北方的面条到底有多少种花样,想走进那 ...
- Java进阶(四十一)多线程讲解
Java多线程讲解 前言 接到菜鸟网络的电话面试,面试官让自己谈一下自己对多线程的理解,现将其内容整理如下. 线程生命周期 Java线程具有五种基本状态 新建状态(New):当线程对象创建后,即进入了 ...
- Mac下hosts文件配置
工作中总会因为莫名其妙的原因,比如Mac下面打不开某网站,但是在windows 7下面却可以,此时只需两步即可完成在Mac下面上网.在Windows下面Win+R,输入cmd,进入命令行,将在wind ...
- 关于AndroidSDK配置时的tools目录下找不到adb.exe的错误
欢迎关注公众号,每天推送Android技术文章,二维码如下:(可扫描) 在配置android SDK的时候,有时会发现在android-sdk-windows\tools目录下并没有adb.exe,这 ...
- Android简易实战教程--第四话《最简单的短信发送器》
首先配置一个布局: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmln ...
- iOS开发基础block的形式讲解
前几个星期,我利用通知写了一个仿京东选择地址的Demo(http://blog.csdn.net/hbblzjy/article/details/52212879),后来看过一篇文章说,尽量少用通知, ...