140. Word Break II 【LeetCode】

问题描述

在这里插入图片描述
现在要你把能形成的句子也打印出来
用递归如下,结果超时

class Solution {
public:
    vector<string> ans;
    void dfs(string str,string s,string t,unordered_set<string>& wordDict)
    {
        if(s.size()==0)
    	{
    		ans.push_back(t.substr(0,t.size()-1));
    		return;
		}
        for(int i=0;i<=s.size();i++)
        {
            if(wordDict.find(s.substr(0,i)) != wordDict.end())
            {
                t += s.substr(0,i);
                dfs(str,s.substr(i),t+" ",wordDict);
                t = t.substr(0,t.size()-i);
            }
        }
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict(wordDict.begin(),wordDict.end());
        dfs(s,s,"",dict);
        return ans;
    }
};

后来参考了大佬的写法,把中途遍历过的字符串对应的句子存起来

class Solution {
public:
    map<string,vector<string> > m;
    vector<string> dfs(string s,unordered_set<string>& wordDict)
    {
        if(m.count(s))  return m[s];
        if(s.empty())  return {""};
        vector<string> ans;
        for (string word : wordDict)
        {
            if(s.substr(0,word.size())== word)
            {
                vector<string> res = dfs(s.substr(word.size()),wordDict);
                for(string str : res)
                    ans.push_back(word + (str.empty() ? "" : " ")+str);
            }
        }
        m[s]=ans;
        return m[s];
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        return dfs(s,wordDict);
    }
};

猜你喜欢

转载自blog.csdn.net/hhhhhh5863/article/details/89235100