题目:

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. C#添加删除防火墙例外(程序、端口)

    一. 添加 COM 引用 在引用里,选择 COM 页, 找到 NetFwTypeLib , 确定即可 二. 添加允许通过防火墙的例外程序 using System; using System.Coll ...

  2. redis在Windows下以后台服务一键搭建集群(多机器)

    redis在Windows下以后台服务一键搭建集群(多机器) 一.概述 此教程介绍如何在windows系统中多台机器之间布置redis集群,同时要以后台服务的模式运行.布置以脚本的形式,一键完成.多台 ...

  3. 送H-1B 及其他I-129 申请别忘用新表

    (梁勇律师事务所,lianglaw.com专稿)移民局从2010年11月23日 更新了申请H-1B 及其他非移民工作签证I-129 表,从2010年12月23日以后收到的I-129表都必须是2010年 ...

  4. cmd中不能输入中文

    在命令行窗口下不能输入中文,只能输入英文,这是因为cmd.exe窗口启动时并没有启动conime.exe进程.事实上,这个进程容易被后门病毒利用,因此网上很多人都把它当成病毒看待,一些网上下载的系统就 ...

  5. int _tmain(int argc, _TCHAR* argv[])

    int _tmain(int argc, _TCHAR* argv[]){ int i; for (i = 0; i<argc; i++) cout<<argv[i]<< ...

  6. PHP与MYSQL结合操作——文章发布系统小项目(实现基本增删查改操作)

    php和mysql在一起几十年了,也是一对老夫老妻了,最近正在对他们的爱情故事进行探讨,并做了一个很简单的小东西——文章发布系统,目的是为了实现mysql对文章的基本增删查改操作 前台展示系统有:文章 ...

  7. 浅析Dagger2依赖注入实现过程

    Dragger2是Android应用开发中一个非常优秀的依赖注入框架.本文主要通过结合Google给出的MVP开发案例todo-mvp-dagger(GitHub连接地址:https://github ...

  8. vue中使用setTimeout

    在vue的函数中使用setTimeout self.distroyTimeout = setTimeout(()=>{ self.initData() },1000) 这时清除setTimeou ...

  9. World Wind Java开发之十二——加载粗制三维模型(ExtrudedPolygon)(转)

    ww可以根据DLG图批量生成假三维模型,这对于小区等特征相似的建筑物模型的构建是非常有用的.下面来看如何一步步实现假三维模型的加载: 1.Shp文件的制作 首先在arcmap下数字化几个建筑物,并新建 ...

  10. CUDA:Supercomputing for the Masses (用于大量数据的超级计算)-第七节

    第七节:使用下一代CUDA硬件,快乐加速度 原文链接 Rob Farber 是西北太平洋国家实验室(Pacific Northwest National Laboratory)的高级科研人员.他在多个 ...