【发布时间】:2020-07-30 20:34:27
【问题描述】:
对于来自 LeetCode https://leetcode.com/problems/word-break-ii/ 的这个问题,我已经看到了下一个解决方案:
class Solution {
private:
unordered_map<string, vector<string>> dp;
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
if(dp.find(s) != dp.end())
return dp[s];
vector<string> result;
for(string w : wordDict)
{
if(s.substr(0, w.length()) == w)
{
if(w.length() == s.length())
result.push_back(w);
else
{
vector<string> temp = wordBreak(s.substr(w.length()), wordDict);
for(string t : temp)
result.push_back(w + " " + t);
}
}
}
dp[s] = result;
return result;
}
};
有人可以帮我理解它是如何工作的吗?我发现这种递归很难理解。
【问题讨论】:
-
一般来说比赛代码不是为了被理解而写的。它旨在快速编写并在特定硬件上快速运行一次。很多时候它不值得学习。
-
理解代码的最好方法是在调试器中启动它并逐行浏览代码。
-
你试过用调试器看看它是如何工作的吗?
标签: c++ algorithm recursion dynamic-programming