Word Break II -- leetcode
来源:互联网 发布:java基础教程 pdf 编辑:程序博客网 时间:2024/06/04 08:08
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"]
.
深度递归(暴力偿试法)
再结合剪枝操作。
剪枝操作思路为:
使用一个数组:breakable[i], 表示从第 i个字符向后直至结束,是否可分解为句子。初始皆为true.
当发现从一个位置不可分隔成数组,则置上标志,以避免后续的重复偿试。
判断不可分隔也很简单,即从一个位置起开始递归后,如果结果集没有增加,则该位置不可分隔。
此代码在leetcode上实际执行时间为4ms。
class Solution {public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> ans; vector<int> breakable(s.size()+1, true); dfs(ans, s, wordDict, "", 0, breakable); return ans; } void dfs(vector<string> &ans, const string &s, const unordered_set<string> &wordDict, string sentence, int start, vector<int> &breakable) { if (start == s.size()) { ans.push_back(sentence); return; } if (!sentence.empty()) sentence.push_back(' '); const int old_size = ans.size(); for (int i=start+1; i<=s.size(); i++) { if (!breakable[i]) continue; const string word(s.substr(start, i-start)); if (wordDict.find(word) != wordDict.end()) { dfs(ans, s, wordDict, sentence + word, i, breakable); } } if (old_size == ans.size()) breakable[start] = false; }};
0 0
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Leetcode: Word Break II
- LeetCode Word Break II
- Word Break II leetcode
- [leetcode]Word Break II
- leetcode -- word break II
- java异常处理
- 一键清除SVN或CVS版本控制目录
- 正确使用Block避免Cycle Retain和Crash
- 关于安装ACCESS 2007 精简版(云端版)出现错误的解决方案
- 浅析Oracle数据恢复操作
- Word Break II -- leetcode
- velocity基本语法
- 启动smb服务器的小技巧
- (android 关机/重启)Android关机/重启流程解析 (2)-----实例解析(多种实现方式)
- JQuery 常用方法经典总结
- PuTTY+Xming实现X11的ssh转发
- 理解OAuth 2.0
- 在你步入职业软件开发生涯那天起就该知道的五件事
- Matlab 的reshape函数