题目:

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的更多相关文章

  1. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  2. 【Unique Paths II】cpp

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  3. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  4. 【Jump Game II 】cpp

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

  5. 【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 ...

  6. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  7. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  8. 【Single Num II】cpp

    题目: Given an array of integers, every element appears three times except for one. Find that single o ...

  9. 【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 ...

随机推荐

  1. git 初始化仓库与远程clone

    使用命令 git –bare init /home/git/myRep.git,初始化化仓库 在gitClient_01上,通过git clone命令进行克隆远程仓库,并在各自的电脑上运行开发. Gi ...

  2. PagedList.Mvc只有一行时不显示分页

    PagedList.Mvc默认总是显示分页,可以通过设置DisplayMode在只有一行时不显示分页 @Html.PagedListPager(Model, page => Url.Action ...

  3. Java 中 Double 相关问题

    在项目当中,对于double类型数据的使用比较频繁.尤其是处理金钱相关的数据,在使用Double类型的数据时,涉及到精度,显示,四舍五入等等问题. 1.  显示问题,当double 数据 小于 0.0 ...

  4. maven+jenkins发布环境

    安装java省略,下面是环境变量 export JAVA_HOME=/usr/java/jdk1.8.0_65/ export PATH=$JAVA_HOME/bin:$PATH export CLA ...

  5. C#调用Python脚本并使用Python的第三方模块

    [转载]http://zh.5long.me/2015/dotnet-call-python/ 前言 InronPython是一种在.NET和Mono上实现的Python语言,使用InronPytho ...

  6. 从.net到java,从基础架构到解决方案。

    这一年,职业生涯中的最大变化,是从.net到java的直接跨越,是从平台架构到解决方案的不断完善. 砥砺前行 初出茅庐,天下无敌.再学三年,寸步难行.很多时候不是别人太强,真的是自己太弱,却不自知. ...

  7. js 生成随机数解决缓存的问题

    对于缓存有一个解决方法是在链接后添加随机数 例如登陆后跳转到链接/home,但是有缓存上次用户的登陆名,于是在/home后面加上一个随机数 var href = '/home?'+Math.rando ...

  8. Django疑难问题

    1页面出现中文报错 :Non-ASCII character '\xe9' in file E:\CPaas\cpaas\views.py 解决:在页面顶部加入#coding=utf-8 2执行syn ...

  9. swift 命名空间实现的设计思考:extension YKKit where Base == String

    设计问题:谁来构造.构造什么.怎么添加新功能 关键词:本体.客体.构造.映射.功能. 别名:桥接变量.型变变量.容器变量.适配变量,构造变量: 目的:添加命名空间.添加新功能. 原则:不修改本体的实现 ...

  10. 简析平衡树(二)——Treap

    前言 学完了替罪羊树,我决定再去学一学\(Treap\).一直听说\(Treap\)很难,我也花了挺久才学会. 简介 \(Treap\)这个名字真的挺有内涵: \(\color{red}{Tree}\ ...