Leetcode dfs Word Break II,leetcodedfs
Word Break II Total Accepted: 15138 Total Submissions: 92228My Submissions
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
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;}