140. Word Break II 分詞 DP
阿新 • • 發佈:2018-12-31
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"]
1.我的解答
參考word break1 dp
前面是判斷dp[i] = (dp[j]==true && s(j...i) in dict)
現在是對於每個位置,用vector記錄前面可以割的位置
然後用dfs找出這些word並連線起來
class Solution { public: void dfs(string s, vector<vector<int>>num, int begin, vector<string>& res, string str){ if(begin == s.size()){ res.push_back(str); return; } for(int i = 0; i < num[begin].size(); i++){ int end = num[begin][i]; string temp = s.substr(begin, end-begin); string strs = str; strs += temp; if(end < s.size()) strs += " "; dfs(s, num, end, res, strs); } } vector<string> wordBreak(string s, unordered_set<string>& wordDict) { int n = s.size(); vector<vector<int>>num(n+1,vector<int>()); num[n].push_back(n); for(int i = n-1; i >= 0; i--){ for(int j = i+1; j <= n; j++){ if(num[j].size() == 0) continue; //有位置存入,相當於true;沒有位置存入,相當於false,直接跳過,體現DP string str = s.substr(i, j-i); if(wordDict.find(str) != wordDict.end()){ num[i].push_back(j); } } } vector<string>res; string str; dfs(s, num, 0, res,str); return res; } };