您的位置:首页 > 其它

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 =
"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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: