ZBLOG

class Solution { public: set visited{}; bool flag = false; vector Resultpath; vector optionalList(string &curWord, vector &wordList) { vector result; for (int i = 0; i < word...

这段代码的问题是递归过程中没有处理好访问记录和路径,导致内存占用过大。以下是对代码进行优化的建议:

  1. 使用unordered_set而不是set来保存visited集合,因为unordered_set具有更快的查找性能。
  2. 在DFS函数中传递visited集合作为参数,避免全局变量的使用。
  3. 在DFS函数中传递path列表作为参数时,应该传递引用或指针,以避免在每次调用时都进行拷贝操作。
  4. 当找到目标单词时,可以提前终止搜索并返回结果,而不必继续进行无效的递归。

修改后的代码如下:

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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9967

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?