Word Break II -- leetcode
2017-08-02 17:09
429 查看
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 =
dict =
A solution is
基本思路:
深度递归(暴力偿试法)
再结合剪枝操作。
剪枝操作思路为:
使用一个数组:breakable[i], 表示从第 i个字符向后直至结束。是否可分解为句子。
初始皆为true.
当发现从一个位置不可分隔成数组。则置上标志,以避免兴许的反复偿试。
推断不可分隔也非常easy,即从一个位置起開始递归后。假设结果集没有添加,则该位置不可分隔。
此代码在leetcode上实际运行时间为4ms。
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.
当发现从一个位置不可分隔成数组。则置上标志,以避免兴许的反复偿试。
推断不可分隔也非常easy,即从一个位置起開始递归后。假设结果集没有添加,则该位置不可分隔。
此代码在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; } };
相关文章推荐
- Leetcode 140 Word Break II
- [leetcode]Word Break II @ Python
- [LeetCode] Word Break II
- *[leetcode]Word Break II
- 【leetcode】Word Break && Word Break II
- LeetCode:Word Break II(DP)
- leetcode - Word Break II
- Word Break II——LeetCode
- LeetCode 140. Word Break II
- LeetCode Word Break II
- leetcode:word break II
- LeetCode | Word Break II
- 【LeetCode】140. Word Break II
- LeetCode_Word Break II
- Leetcode Word Break II
- LeetCode – Word Break II (Java)
- leetcode做题总结,回溯法(N-Queens, N-QueensII,Combination SumI&II,wordbreak II, SubsetsI&II)
- 每天一道算法题(七)Leetcode – Word BreakII (Java)
- LeetCode_DP_Word Break II
- LeetCode140. Word Break II