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

记忆化搜索,将对应位置之后的所有的string保存下来,供下一次递归使用,减少计算量

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        int max_len = 0;
        for (auto c : dict)
        {
            if (c.size()>max_len)
                max_len = c.size();
        }
        int flag = 1;
        unordered_map<int, vector<string>> map;
        vector<string> res = recurfind(s, dict, 0, max_len, flag, map);
        return res;
    }

    vector<string>  recurfind(string &s, unordered_set<string> &dict, int beg, int max_len, int &flag, unordered_map<int, vector<string>> &map){
        if (flag == 0)
            return vector<string>{};
        if (beg >= s.size() && flag)
            return vector <string> {string()};

        vector<string> vec;
        flag = 0;
        for (int i = 1; i <= max_len&&beg + i <= s.size(); ++i)
        {
            if (dict.count(s.substr(beg, i))){
                flag = 1;
                string str = s.substr(beg, i) + " ";
                vector<string> res;
                if (map.count(beg + i))
                    res = map[beg + i];
                else
                    res = recurfind(s, dict, beg + i, max_len, flag, map);
                if (flag == 0)
                {
                    continue;
                }
                for (auto c : res){
                    if (c.size() == 0)
                        c.insert(0, str.substr(0, str.size() - 1));
                    else
                        c.insert(0, str);
                    vec.push_back(c);
                }
            }
        }
        map[beg] = vec;
        return vec;
    }
};

你可能感兴趣的:(leetcode,string)