【Word Break II】cpp
题目:
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>& wordDict)
{
vector<string> ret;
vector<string> tmp;
vector<bool> possible(s.size(), true);
Solution::dfs( possible, wordDict, ret, tmp, s, , s.size()-);
return ret;
}
static void dfs(
vector<bool>& possible, // possible[i] : if s[i~end] can be possible word broken
unordered_set<string>& wordDict,
vector<string>& ret,
vector<string>& tmp,
string& s, int begin, int end )
{
if ( begin>end )
{
string str = "";
for ( int i=; i<tmp.size(); ++i ) { str = str + tmp[i] + " "; }
ret.push_back(str.substr(,str.size()-));
}
for ( int i=begin; i<=end; ++i )
{
if ( wordDict.find(s.substr(begin,i-begin+))!=wordDict.end() && possible[i] )
{
tmp.push_back(s.substr(begin,i-begin+));
int oriSolution = ret.size();
Solution::dfs( possible, wordDict, ret, tmp, s, i+, end);
if ( oriSolution==ret.size()) possible[i]=false;
tmp.pop_back();
}
}
}
};
tips:
其实在word break i这道题的时候就想用dfs做,但是会超时。
word break ii这道题是求所有可行解,就尤其想用dfs来做。
一开始写了一版裸dfs的代码,发现会超时:原因是没有剪枝。
这里学习了一下大神的剪枝技巧(http://fisherlei.blogspot.sg/2013/11/leetcode-wordbreak-ii-solution.html)
这里的possible[i] 代表的是 s[i+1:s.size()-1] 可否被给定的wordDict来word break。翻译过来就是,从i往后(不包括i)是否行可以被wordDict表示。
这个思路很精妙:
1. 从给定当前点往后看,看能否满足条件。这样dfs下次再走到这个点的时候,就知道是否可以往下走了。
2. 为什么不把possible[i]当成s[0~i]是否满足条件呢?因为能来到位置i的方式有很多种,一种方式行不通不代表其他方式行不通
3. 由i往后,一直到end,已经把所有可能走到最后的方式都包括了,如果所有可能走到最后的方式中都行不通,那就是肯定行不通了
4. 如何记录是否行得通了呢?我就是卡在这里了,没想到太好的办法。这时学习了大神的办法,比较下解集的个数:如果个数没变,那肯定是行不通了。
===============================================
第二次过这道题,复习遍原来的方法。
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict)
{
vector<string> ret;
vector<string> tmp;
vector<bool> possible(s.size(),true);
Solution::dfs(ret, tmp, , s.size()-, s, wordDict, possible);
return ret;
}
static void dfs(
vector<string>& ret,
vector<string>& tmp,
int begin,
int end,
string& s,
unordered_set<string>& wordDict,
vector<bool>& possible
)
{
if ( begin>end )
{
string str = "";
for ( int i=; i<tmp.size(); ++i ) str += tmp[i] + " ";
ret.push_back(str.substr(,str.size()-));
return;
}
for ( int i=begin; i<=end; ++i )
{
if ( wordDict.find(s.substr(begin, i-begin+))!=wordDict.end() && possible[i] )
{
tmp.push_back(s.substr(begin, i-begin+));
int pre = ret.size();
Solution::dfs(ret, tmp, i+, end, s, wordDict, possible);
if ( ret.size()==pre ) possible[i] = false;
tmp.pop_back();
}
}
}
};
【Word Break II】cpp的更多相关文章
- 【Word Ladder II】cpp
题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- 【Unique Paths II】cpp
题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...
- 【palindrome partitioning II】cpp
题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...
- 【Jump Game II 】cpp
题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...
- 【Path Sum II】cpp
题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...
- 【Spiral Matrix II】cpp
题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...
- 【Combination Sum II 】cpp
题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...
- 【Single Num II】cpp
题目: Given an array of integers, every element appears three times except for one. Find that single o ...
- 【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 ...
随机推荐
- TCP 协议中的 Window Size与吞吐量
原地址:http://blog.sina.com.cn/s/blog_c5c2d6690102wpxl.html TCP协议中影响实际业务流量的参数很多,这里主要分析一下窗口的影响. TCP窗口目的 ...
- uvm_tlm——TLM1事务级建模方法(一)
TLM(事务级建模方法,Transaction-level modeling)是一种高级的数字系统模型化方法,它将模型间的通信细节与函数单元或通信架构的细节分离开来.通信机制(如总线或者FIFO)被建 ...
- Neo4j-3.0.3 (Debian 8)
平台: Ubuntu 类型: 虚拟机镜像 软件包: neo4j-3.0.3 basic software database graph database infrastructure neo4j op ...
- webstorm下载激活汉化
下载 官方下载地址:https://www.jetbrains.com/webstorm/ 激活 参考http://blog.csdn.net/it_talk/article/details/5244 ...
- HDU 1085 Holding Bin-Laden Captive! 活捉本拉登(普通型母函数)
题意: 有面值分别为1.2.5的硬币,分别有num_1.num_2.num_5个,问不能组成的最小面值是多少?(0<=每种硬币个数<=1000,组成的面值>0) 思路: 母函数解决. ...
- NopCommerce 3.80框架研究(三)替换tinymce 为KindEditor
NopCommerce 自带的编辑器tinymce 功能不是很全.所以尝试将其替换为功能更强大的 KindEditor 并替实现文件上传和在线浏览功能 首先下载 并解压到如下位置 请注意这里是部署在N ...
- pat甲级1123
1123 Is It a Complete AVL Tree(30 分) An AVL tree is a self-balancing binary search tree. In an AVL t ...
- 如何在Java代码中使用SAP云平台CloudFoundry环境的环境变量
本文使用的例子源代码在我的github上. 在我的公众号文章在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务介绍了如何通过Cloud Connector ...
- IOS UIButton常用属性
//1.添加按钮 UIButton *nameView=[UIButton buttonWithType:UIButtonTypeCustom]; //nameView.backgroundColor ...
- hdu-3371 Connect the Cities---kruskal
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3371 题目大意: 给n个城市,m条路,k组已知路,求最小费用联通所有城市: 解题思路: kruska ...