首页 > 代码库 > Leetcode dfs Word Break II
Leetcode dfs Word Break II
Word Break II
Total Accepted: 15138 Total Submissions: 92228My SubmissionsGiven 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
void dfs(int start, string partition);
start表示当前要分割的字符串s[start:],
设 k将 s分割为s[:k]和s[k:],则 0 < k <= s.size() 且 s[:k]存在字典dict中
按上面这样的思路直接做会超时,可采用dfs + 剪枝的思路
增加一个bool数组 possible[k] 表示字符串s[k:]是否可用字典里的单词来分割
unordered_set<string> _dict; vector<string> res; vector<bool> possible; string _s; void dfs(int start, string partition){ if(start >= _s.size()){ res.push_back(partition.substr(1, partition.size() - 1)); return; } for(int k = start + 1; k <= _s.size(); ++k){ if(possible[k] && _dict.find(_s.substr(start, k - start)) != _dict.end()){ //剪枝 int size_before = res.size(); dfs(k , partition + " " + _s.substr(start, k - start)); if(res.size() == size_before) possible[k] = false; //剪枝 } } } vector<string> wordBreak(string s, unordered_set<string> &dict){ _dict = dict; _s = s; possible = vector<bool>(s.size() + 1, true); dfs(0, ""); return res; }
Leetcode dfs Word Break II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。