1. 程式人生 > 實用技巧 >LeetCode 140. 單詞拆分 II dfs 雜湊

LeetCode 140. 單詞拆分 II dfs 雜湊

地址https://leetcode-cn.com/problems/word-break-ii/

給定一個非空字串 s 和一個包含非空單詞列表的字典 wordDict,在字串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。

說明:

分隔時可以重複使用字典中的單詞。
你可以假設字典中沒有重複的單詞。
示例 1:

輸入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
輸出:
[
 "cats and dog",
 "cat sand dog"
]
示例 2:

輸入:
s = "
pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] 輸出: [ "pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] 解釋: 注意你可以重複使用字典中的單詞。 示例3: 輸入: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] 輸出: []

演算法1
上來就是一陣操作 暴力DFS
果然就是TLE了。還是非常嚴重的TLE那種
後面利用雜湊記錄對應的字串拆解成功的方案 才能AC

C++ 程式碼

class Solution {
public:
    unordered_map<string, vector<string>> mm;

    vector<string> dfs(string s, const vector<string>& wordDict){
        if (mm.count(s) != 0) return mm[s];
        if (s.empty()) return {""};
        vector<string> ret;
        for
(auto& e : wordDict) { if (e[0] == s[0] && s.substr(0, e.size()) == e) { vector<string> last; last = dfs(s.substr(e.size()), wordDict); for (auto& ee : last) ret.push_back(e + (ee.empty() ? "" : " ") + ee); } } mm[s] = ret; return ret; } vector<string> wordBreak(string s, vector<string>& wordDict) { dfs(s, wordDict); vector<string> ans = mm[s]; return ans; } };