140. Word Break II

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
};

 

以上是关于140. Word Break II的主要内容,如果未能解决你的问题,请参考以下文章

140. Word Break II

leetcode 140 word break II 单词拆分2

140. Word Break II

140. Word Break II

140. Word Break II

140. Word Break II