leetcode 140: Word Break II

来源:互联网 发布:网络鸡汤到底什么意思 编辑:程序博客网 时间:2024/04/28 12:55

Use DP + DFS to go through all paths. Only DFS will result in TLE.

class Solution {public:    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {        int len=s.length();        vector<bool> dp(len,0);        unordered_map<string,vector<string> > children;        for(int i=0;i<len;i++)        {            string temp=s.substr(0,i+1);            if(wordDict.find(temp)!=wordDict.end())                dp[i]=1;            else            {                for(int j=0;j<i;j++)                {                    if(dp[j]&&wordDict.find(s.substr(j+1,i-j))!=wordDict.end())                    {                        dp[i]=1;                        break;                    }                }            }        }        vector<string> res;        vector<string> path;        dfs(s,wordDict,dp,res,path);        return res;    }    void dfs(string s,unordered_set<string>& wordDict,vector<bool>& dp,vector<string>& res,vector<string>& path)    {        for(int i=s.length()-2;i>=0;i--)        {            if(dp[i]&&wordDict.find(s.substr(i+1))!=wordDict.end())            {                path.push_back(s.substr(i+1));                dfs(s.substr(0,i+1),wordDict,dp,res,path);                path.pop_back();            }        }        if(wordDict.find(s)!=wordDict.end())        {            string temp;            if(path.size()==0)                temp=s;            else            {                temp=s;                for(int i=path.size()-1;i>=0;i--)                    temp+=' '+path[i];            }            res.push_back(temp);        }    }};


0 0
原创粉丝点击