ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 140 Word Break II 记忆化搜索 [Hard]

2022-08-01 04:00:08  阅读:169  来源: 互联网

标签:end dictionary 140 II vector mp ans wordDict Word


Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Solution

这里我们需要输出所有的方案。我们考虑记忆化搜索。具体来说,我们用一个 \(map\) 来维护字符串 \(s\) 对应的方案 \(map[s]\).

在搜索的过程中,我们按照分割的位置将字符串在 \(i\) 地方切割,如果后半段在 wordDict里面,那我们按照同样的思路对前面进行切割

点击查看代码
class Solution {
private:
    unordered_map<string, vector<string>> mp;
    
    vector<string> comb(string w, vector<string> v){
        for(int i=0;i<v.size();i++){
            v[i] = v[i]+" "+w;
        }
        return v;
    }
    
    
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        // memorize
        if(mp.count(s)) return mp[s];
        vector<string> ans;
        
           if(find(wordDict.begin(),wordDict.end(),s)!=wordDict.end())ans.push_back(s);
        
        for(int i=1;i<s.length();i++){
            string w = s.substr(i);
            if(find(wordDict.begin(), wordDict.end(),w)!=wordDict.end()){
                // w exists
                string resd = s.substr(0,i);
                vector<string> v = comb(w, wordBreak(resd,wordDict));
                ans.insert(ans.end(),v.begin(), v.end());
            }
        }
        mp[s] = ans;
        return ans;
    }
};

标签:end,dictionary,140,II,vector,mp,ans,wordDict,Word
来源: https://www.cnblogs.com/xinyu04/p/16538817.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有