题目:

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. repair table

    mysql> show create table lixl;+-------+---------------------------------------------------------- ...

  2. POJ 1769 Minimizing maximizer (线段树优化dp)

    dp[i = 前i中sorter][j = 将min移动到j位置] = 最短的sorter序列. 对于sorteri只会更新它右边端点r的位置,因此可以把数组改成一维的,dp[r] = min(dp[ ...

  3. 2018.6.10 Oracle数据库常见的错误汇总

    1.ClassNoFoundException 找不到注册驱动 可能原因:1>驱动名称不对 2>没有导入数据库驱动包 2.SQl 语句中可以使用任何有效的函数,函数操作的列,必须指定别名, ...

  4. 2018.5.21 . XMLSpy激活的方法

    127.0.0.1 altova.com #XMLspy 127.0.0.1 www.altova.com #XMLspy 127.0.0.1 link.altova.com #XMLspy 追加加到 ...

  5. OO第四单元总结

    单元架构设计 本单元OO作业主要涉及两个过程,即先根据输入的elements数组建立UML存储模型,而后基于这个模型实现一系列查询判断功能.汲取上单元的经验,建模过程中模型数据容器的选择依据要求实现的 ...

  6. 题解 P1137 【旅行计划】

    传送门 很显然,每个点的答案是它所有前驱节点的答案加1,即f[i]=max(f[i],f[j]+1); 考虑空间复杂度用邻接表存图,在拓扑排序同时DP就好了 #include<iostream& ...

  7. install ipython-notebook

    http://it.010lm.com/os/LINUX/182036.html ipython[notebook]安装(Linux平台) 1. 环境 操作系统:ubuntukylin 2. 操作步骤 ...

  8. 简述apache,php,mysql三者的关系

    转自:http://blog.csdn.net/w1365966490/article/details/8218959 Apache web 服务器软件.同类产品有微软的 IIS 等.功能是让某台电脑 ...

  9. Bootstrap 折叠(collapse)插件面板

    折叠插件(collapse)可以很容易地让页面区域折叠起来, 无论您是用它来创建折叠导航还是内容面板,它都允许很多内容选项. 您可以使用折叠插件 1.创建可折叠的分组或折叠的面板 <!DOCTY ...

  10. webSocket使用心跳包实现断线重连

    首先new一个webscoket的连接 let noticeSocketLink = new WebSocket(‘webSocket的地址’) 这里是连接成功之后的操作 linkNoticeWebs ...