140. Word Break II 分词 DP

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>num, int begin, vector& 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 wordBreak(string s, unordered_set& wordDict) {
        int n = s.size();
        vector>num(n+1,vector());
        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);
                }
            }
        }
        vectorres;
        string str;
        dfs(s, num, 0, res,str);
        return res;
    }
};


你可能感兴趣的:(leetcode,dp)