1. 程式人生 > >[Leetcode] 140. Word Break II 解題報告

[Leetcode] 140. Word Break II 解題報告

題目

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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,但是由於字串中可能存在相同的子串,所以我們在DFS搜尋的過程中還需要記憶已經找到的結果,這樣可以大大提高效率(否則過不了大資料)。在DFS的搜尋過程中,我們首先判斷其前i個字元所構成的子字串是否存在於字典中,如果是,再遞迴地搜尋從i之後的子串所能構成的結果陣列;遞迴完成之後的關鍵一步就是合成結果,也就是將前i個字元所構成的子字串和遞迴返回的結果合併起來,作為最終結果。當然在返回之前不能忘記把它放在雜湊列表中。

程式碼

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        return dfs(s, wordDict);
    }
private:
    vector<string> dfs(string s, unordered_set<string>& wordDict) {
        if(hash.count(s) > 0) {
            return hash[s];
        }
        vector<string> ret;
        if(wordDict.count(s) > 0) {
            ret.push_back(s);
        }
        for(int i = 1; i < s.length(); ++i) {
            string first = s.substr(0, i);
            if(wordDict.count(first) > 0) {
                vector<string> ans = dfs(s.substr(i), wordDict);
                for(auto val : ans) {
                    ret.push_back(first + " " + val);
                }
            }
        }
        hash[s] = ret;
        return ret;
    }
    unordered_map<string, vector<string>> hash;
};