[回溯+剪枝]leetcode140:单词拆分 Ⅱ(hard)

编程入门 行业动态 更新时间:2024-10-26 05:32:23

[回溯+剪枝]leetcode140:<a href=https://www.elefans.com/category/jswz/34/1769906.html style=单词拆分 Ⅱ(hard)"/>

[回溯+剪枝]leetcode140:单词拆分 Ⅱ(hard)

题目:

140. 单词拆分 II

题解:

  • 回溯+剪枝
  • 若使用回溯法一般框架,对于aaa...aaa这种字符串时,会造成大量重复计算从而导致超时现象,所以我们需要加个map存放<s,result>,这样达到剪枝的效果,优化时间。

代码如下:

class Solution {
public:vector<string> wordBreak(string s, vector<string>& wordDict) {unordered_map<string,vector<string>> m;return backtrack(m,s,wordDict);}vector<string> backtrack(unordered_map<string,vector<string>>& m,string s,vector<string>& wordDict){if(m.count(s))return m[s];//记忆化,避免重复搜索导致超时现象if(s.empty())return {""};//选择列表已空,表示生成一个可行解vector<string> result;for(const auto& word:wordDict){if(s.substr(0,word.size())!=word)continue;//剪枝,判断word是否为s的前缀//进入下一步决策,s.substr(word.size())选择列表减小vector<string> temp=backtrack(m,s.substr(word.size()),wordDict);for(const auto& it:temp){result.push_back(word+(it.empty()?"":" "+it));}}m[s]=result;return result;}
};

更多推荐

[回溯+剪枝]leetcode140:单词拆分 Ⅱ(hard)

本文发布于:2023-07-28 18:53:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279937.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   hard

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!