• 30 Day Challenge Day 17 | Leetcode 126. Word Ladder II


    题解

    Hard

    难死了。

    class Solution {
    public:
        vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
            unordered_set<string> dict(wordList.begin(), wordList.end());
            
            vector<vector<string>> res;
    
            queue<vector<string>> paths;
            vector<string> path;
            
            path.push_back(beginWord);
            paths.push(path);
            
            if(!dict.count(endWord)) return {};
            
            int level = 1, min_level = INT_MAX;
            
            unordered_set<string> words;
    
            while(!paths.empty()) {
                auto t = paths.front();
                paths.pop();
    
                if (t.size() > level) {
                    for (string w : words) dict.erase(w);
                    words.clear();
                    level = t.size();
                    if (level > min_level) break;
                }
    
                string last = t.back();
    
                for(int k = 0; k < last.size(); k++) {
                    string new_last = last;
                    for(int c = 'a'; c <= 'z'; c++) {
                        new_last[k] = c;
                        if(!dict.count(new_last)) continue;
                        words.insert(new_last);
                        vector<string> cur_path = t;
                        cur_path.push_back(new_last);
                        if(new_last == endWord) {
                            res.push_back(cur_path);
                            min_level = level;
                        } else {
                            paths.push(cur_path);
                        }
                    }
                }
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    idea 相关
    dns 相关
    bash 相关
    建造者模式(Builder)
    C#中out 及 ref 区别
    C# 2.0新特性
    Asp.net.Ajax控件学习
    装饰模式(Decorator Pattern)
    职责链模式(Chain of Responsibility Pattern)
    面向对象
  • 原文地址:https://www.cnblogs.com/casperwin/p/13760993.html
Copyright © 2020-2023  润新知