Word Break II

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

动态规划标记好可以划分的区域之后深搜

class Solution {
public:
    void dfs(vector<string>&ans,vector<vector<bool>>& record,string& s,vector<string>&path,int end){
        if(end<0){
            string temp;
            for(auto a:path) temp=a+' '+temp;
            temp=temp.substr(0,temp.size()-1);
            ans.push_back(temp);
        }
        for(int i=end;i>=0;i--){
            if(record[end][i]){
                path.push_back(s.substr(i,end-i+1));
                dfs(ans,record,s,path,i-1);
                path.pop_back();
            }
        }
    }
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        int l=s.size();
        vector<bool> tag(l+1,false);
        tag[0]=true;
        vector<vector<bool>> record(l,vector<bool>(l,false));
        for(int i=0;i<l;i++)
        for(int j=i;j>=0;j--)
            if(tag[j]&&dict.find(s.substr(j,i-j+1))!=dict.end()) tag[i+1]=record[i][j]=true;
        vector<string> result;
        vector<string> path;
        dfs(result,record,s,path,l-1);
        return result;
    }
};

你可能感兴趣的:(LeetCode,算法,动态规划,DFS)