solution.cpp 804 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
class Solution
{
public:
    vector<string> wordBreak(string s, vector<string> &wordDict)
    {
        unordered_map<string, vector<string>> m;
        return helper(s, wordDict, m);
    }
    vector<string> helper(string s, vector<string> &wordDict, unordered_map<string, vector<string>> &m)
    {
        if (m.count(s))
            return m[s];
        if (s.empty())
            return {""};
        vector<string> ans;
        for (string word : wordDict)
        {
            if (word != s.substr(0, word.size()))
                continue;
            vector<string> res = helper(s.substr(word.size()), wordDict, m);
            for (string str : res)
            {
                ans.push_back(word + (str.empty() ? "" : " ") + str);
            }
        }
        return m[s] = ans;
    }
};