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"].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

 

class Solution {
public:
    vector<string>combine(string word, vector<string> prev) {
        for(int i = 0; i < prev.size(); i++) {
            prev[i]+=" "+word;
        }
        return prev;
    }
    vector<string> dfs(string s, unordered_set<string>&wordDicts) {
        if(hash.count(s))return hash[s];
        vector<string>res;
        if(wordDicts.count(s))res.push_back(s);
        for(int i = 1; i < s.length(); i++) {
            string word = s.substr(i);
            if(wordDicts.count(word)) {
                string rem = s.substr(0,i);
                vector<string> prev=combine(word,dfs(rem,wordDicts));
                res.insert(res.end(),prev.begin(),prev.end());
            }
        }
        hash[s] = res;
        return res;
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string>wordDicts(wordDict.begin(), wordDict.end()); 
        return dfs(s, wordDicts);
    }
private:
    unordered_map<string, vector<string>>hash;
};

 

posted @ 2017-10-21 23:34  Tsunami_lj  阅读(108)  评论(0编辑  收藏  举报