博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] 140. Word Break II 解题报告
阅读量:3676 次
发布时间:2019-05-21

本文共 1718 字,大约阅读时间需要 5 分钟。

题目链接:https://leetcode.com/problems/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"].

思路: DFS+部分剪枝, 搜索的时候记录后面的状态, 如果后面不能搜到, 那么就直接返回了, 否则就进行下去. 其实这样的效率并不高, 因为剪枝并不完全, 即后面可以找到的话, 还要再搜一遍. 估计数据量并不大. 

代码如下:

class Solution {public:    void DFS(string& s, unordered_set
& wordDict, string str, int k) { if(k >= s.size()) result.push_back(str.substr(1)); if(hash.count(k) && hash[k] == false) return; for(int i = k; i < s.size(); i++) { string tem = s.substr(k, i-k+1); if(wordDict.count(tem)) { int len = result.size(); DFS(s, wordDict, str + " " + tem, i+1); hash[i+1] = (len != result.size()); } } } vector
wordBreak(string s, unordered_set
& wordDict) { DFS(s, wordDict, "", 0); return result; }private: vector
result; unordered_map
hash;};

所以还有一种更为彻底的bottom-up如下:

class Solution {public:    vector
wordBreak(string s, unordered_set
& dict) { if(hash.count(s)) return hash[s]; vector
result; if(dict.count(s)) result.push_back(s); for(int i=1; i
vec = wordBreak(s.substr(0, i), dict); for(auto val: vec) result.push_back(val+" " +word); } return hash[s]=result; } private: unordered_map
> hash;};

转载地址:http://eilbn.baihongyu.com/

你可能感兴趣的文章
完美解决:Ubuntu 12.04右键没有打开终端选项
查看>>
快速理解:memmove和memcopy的区别
查看>>
strsep函数详解
查看>>
秒懂之atoi()函数!
查看>>
一分钟快速理解:模拟信号和数字信号!
查看>>
MQTT之QoS
查看>>
【JavaWeb开发】"web应用程序的根目录"与"web站点的根目录"的分析
查看>>
【JavaWeb开发】EL表达式和JSTL标签的使用
查看>>
Spring学习(6)-Spring Bean的生命周期
查看>>
Spring学习(8)-AOP之ProxyFactoryBean、RegexMethodPointcutAdvisor、BeanNameAutoProxyCreator
查看>>
Spring学习(9)-AOP之使用aop:config标签
查看>>
【JavaWeb】常见数据库和JDBC错误的解决思路
查看>>
springmvc的静态资源无法访问解决方法(基本全面)
查看>>
【记坑】freemarker拿不到对象的值
查看>>
Maven基础学习(全面)
查看>>
oracle之40道经典的sql练习
查看>>
最详细的Spring-data-jpa入门(一)
查看>>
win7/win10下的jdk的安装和环境变量的配置
查看>>
PAT乙级_1077 互评成绩计算 (20 分)_python
查看>>
PAT乙级_1088 三人行 (20 分)_python
查看>>