这段代码的问题是递归过程中没有处理好访问记录和路径,导致内存占用过大。以下是对代码进行优化的建议:
- 使用unordered_set而不是set来保存visited集合,因为unordered_set具有更快的查找性能。
- 在DFS函数中传递visited集合作为参数,避免全局变量的使用。
- 在DFS函数中传递path列表作为参数时,应该传递引用或指针,以避免在每次调用时都进行拷贝操作。
- 当找到目标单词时,可以提前终止搜索并返回结果,而不必继续进行无效的递归。
修改后的代码如下:
class Solution {
public:
unordered_set<string> visited;
bool flag = false;
vector<string> Resultpath;
vector<string> optionalList(string &curWord, vector<string> &wordList) {
vector<string> result;
for (int i = 0; i < wordList.size(); i++) {
int count = 0;
for (int j = 0; j < curWord.size(); j++) {
if (curWord[j] != wordList[i][j]) count++;
}
if ((count == 1) && (visited.find(wordList[i]) == visited.end())) {
result.push_back(wordList[i]);
}
}
return result;
}
void DFS(string curWord, string targetWord, vector<string> &wordList, vector<string> &path, unordered_set<string>& visited) {
if (flag) return;
if (curWord == targetWord) {
path.push_back(curWord);
Resultpath = path;
flag = true;
return;
}
path.push_back(curWord);
visited.insert(curWord);
vector<string> List = optionalList(curWord, wordList);
for (const auto item : List) {
if (!flag) {
DFS(item, targetWord, wordList, path, visited);
}
}
path.pop_back();
}
vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());
DFS(beginWord, endWord, wordList, vector<string>{}, visited);
return Resultpath;
}
};
通过使用unordered_set、传递引用或指针以及提前终止搜索等优化,应该可以减少内存的占用并避免超出限制。
内容由零声教学AI助手提供,问题来源于学员提问