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;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值