leetcode刷题.140. 单词拆分 II.每日打卡

leetcode刷题.140. 单词拆分 II.每日打卡_第1张图片

回溯法 + 记忆化

代码: 

class Solution140_hard {
public:
        vector wordBreak(string s, vector& wordDict) {

                if (s.empty())
                        return {};

                unordered_set wordSet;
                unordered_map> memorys;

                for (int i = 0; i < wordDict.size(); i++) {
                        wordSet.insert(wordDict[i]);
                }
                return recursion(s, 0, wordSet, memorys);
        }
private:
        vector recursion(const string &s, int index, unordered_set& wordDict, unordered_map> &memorys) {

                if (index == s.size())
                        return {""};

                unordered_map>::iterator it = memorys.find(index);
                if (it != memorys.end()) {
                        return it->second;
                }

                vector strlist;
                for (int i = index + 1; i <= s.length(); i++) {
                        if (wordDict.find(s.substr(index, i - index)) != wordDict.end()) {

                                vector tmpstr = recursion(s, i, wordDict, memorys);
                                memorys[i] = tmpstr;

                                for (int j = 0; j < tmpstr.size(); j++)
                                        if (tmpstr[j].size())
                                                strlist.push_back(s.substr(index, i - index) + " " + tmpstr[j]);
                                        else
                                                strlist.push_back(s.substr(index, i - index));
                        }
                }
                return strlist;
        }
};

 

你可能感兴趣的:(【算法】,【leetcode刷题】)