LeetCode140: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"]
.
解题思路:
这道题是上一道题Word Break升级版,难度更大些,需要用DP+DFS解决
这里采用DP中的自底向上实现,dp[i]表示前i个字符能否进行Wordbreak。当求解dp[i]时,可利用已经求解的dp[i-1],
dp[i-2]…dp[1],dp[0]进行求解。
对于dp[n]的求解,我们可以将n个字符进行切分求解,分为前i个字符和后n-i个字符,i可以为(0,1,2,3,4…n-1)
假设i为1时,可根据dp[i]和后面的n-1个字符组成的单词是否在dict中来判断dp[n],只要i(0,1,2,3,4…n-1)其中一种
情况为真,则dp[n]为true,表示可以进行workbreak。
因为本题需要重构结果,所以必须要有一个数据结构来保存每段长度的切割方案,这里我用unordered_map<int, vector<int> >进行保存,key为字符长度,vector保存该key对应的切割方案。
如何求得unordered_map<int, vector<int> >中的值呢?那就应该利用求解dp[i]时,每当有一种切割方案使得dp[i]为true时,将其对应的切割位置存放到i对应的vector中,待之后用于结果重构。
unordered_map<int, vector<int> >求得后,接下来是采用DFS算法进行结果重构,如代码执行结果图,当长度为10时,有一种切割方案,即在长度为7的位置进行切割,然后长度为7的切割方案又有两种3和4,长度为3和4时,切割方案都为0,所以采用DFS时,遍历顺序为7,3,0然后获得一种结果,之后回溯到7,4,因为4的切割方案为0,所以为7,4,0,又是一种结果。
实现代码:
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
using namespace std; /*
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"].
*/
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> retvec;
if(s.size() == || dict.size() == )
return retvec;
int len = s.size();
vector<bool> dp(len+, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread
unordered_map<int, vector<int> > hash_map;// 存放使得dp[i]为true的切割方案
dp[] = true;
for(int i = ; i <= len; i++)
{
vector<int> vec;
for(int j = ; j < i; j++)
{
if(dp[j] && dict.count(s.substr(j, i-j)) == )//对前i个字符进行切分时,只要有一种情况为true,则dp[i]=true
{
dp[i] = true;
vec.push_back(j);//放使得dp[i]为true的切割方案
}
}
hash_map[i] = vec;
} for(int k = ; k <= len; k++)
{
vector<int> tvec = hash_map[k];
cout<<k<<":";
vector<int>::iterator iter;
for(iter = tvec.begin(); iter != tvec.end(); ++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
} vector<int> curVec;
getResult(hash_map, s, len, retvec, curVec);
return retvec; } //采用DFS解决
void getResult(unordered_map<int, vector<int> > &hash_map,string s, int len, vector<string> &retvec, vector<int> &curVec)
{
if(len == )
{
string t;
int start = ;
for(int i = curVec.size()-; i >= ; i--)
{
int c = curVec[i];
t += s.substr(start, c-start);
t += " ";
start = c;
}
t += s.substr(curVec[]);
retvec.push_back(t);
return ;
}
vector<int> tvec = hash_map[len];
vector<int>::iterator iter;
for(iter = tvec.begin(); iter != tvec.end(); ++iter)
{
curVec.push_back(*iter);
getResult(hash_map, s, *iter, retvec, curVec);
curVec.pop_back();
} } }; int main(void)
{
string s("catsanddog");
unordered_set<string> dict;
dict.insert("cat");
dict.insert("cats");
dict.insert("and");
dict.insert("sand");
dict.insert("dog"); Solution solution;
vector<string> retvec = solution.wordBreak(s, dict);
vector<string>::iterator iter;
for(iter = retvec.begin(); iter != retvec.end(); ++iter)
cout<<*iter<<endl; return ;
}
执行结果:
LeetCode140:Word Break II的更多相关文章
- LeetCode之“动态规划”:Word Break && Word Break II
1. Word Break 题目链接 题目要求: Given a string s and a dictionary of words dict, determine if s can be seg ...
- 17. Word Break && Word Break II
Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a s ...
- 【LeetCode】140. Word Break II
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- LeetCode: Word Break II 解题报告
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- [Leetcode Week9]Word Break II
Word Break II 题解 题目来源:https://leetcode.com/problems/word-break-ii/description/ Description Given a n ...
- 【Word Break II】cpp
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- 140. Word Break II(hard)
欢迎fork and star:Nowcoder-Repository-github 140. Word Break II 题目: Given a non-empty string s and a d ...
- [LeetCode] Word Break II 拆分词句之二
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- 【leetcode】Word Break II
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
随机推荐
- SVN常见问题I
TortoiseSVN ->Settings 把权限给清空,不让用户A的权限再保留在里面 右键->SVN Checkout 之后需要在A账户和B账户之间来回切换
- Codeforces Beta Round #14 (Div. 2)
Codeforces Beta Round #14 (Div. 2) http://codeforces.com/contest/14 A 找最大最小的行列值即可 #include<bits/s ...
- Java实现聚类算法k-means
2016-07 java简单实现聚类算法 但是有一个小问题,,,,我其实每次迭代之后(就是达不到我的收敛标准之前,聚类中心的误差达不到指定小的时候),虽然重新算了聚类中心,但是其实我的那些点并没有变, ...
- 用HttpClient发送HTTPS请求报SSLException: Certificate for <域名> doesn't match any of the subject alternative names问题的解决
最近用server酱-PushBear做消息自动推送,用apache HttpClient做https的get请求,但是代码上到服务器端就报javax.net.ssl.SSLException: Ce ...
- Gridview中 LinkButton删除以及自带删除
<asp:LinkButton ID="lbtnDel" OnClientClick="return confirm('删除新闻会连同其下评论一起删除,是否删除?' ...
- ef linq 访问视图返回结果重复
根据检测到的语句查询和linq查询出来的结果不一致,linq查询出重复的数据,原因不明,已改用ef直接查询视图,也许以后某一天突然就解决了,先mark下.
- 我对于UI设计这个领域的理解
User Interface(UI),包括三部分用户.界面以及用户与界面之间的交互关系.UI设计则是指对软件的人机交互.操作逻辑.界面美观的整体设计. 如何看待UI设计这个领域? 任何一个行业的出现都 ...
- Fiddler的钩子hook导致电脑无法连上网络
今天,电脑怎么都无法连上网络,重启了几次电脑也不行,网络环境是没有问题的,后来同事告诉我,Fiddler有一个BUG,就是Fiddler获取钩子之后没有释放掉,必须启动Fiddler,再关闭Fiddl ...
- Jmeter的一个jmx文件(备忘)
<?xml version="1.0" encoding="UTF-8"?> <jmeterTestPlan version="1. ...
- c++11 stl 学习之 pair
pair以模板的方式存储两个数据 namespace std {template <typename T1, typename T2>struct pair {// memberT1 fi ...