zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    Nginx配置文件的路径
    有关Tomcat 8.5版本文件上传后无权限访问的问题
    常见HTTP状态码列表
    服务器BMC(带外)
    CDN问题
    PECE
    linux系统概述
    干货--整蛊你的舍友
    arp请求与回复
    huawei oceanstor
  • 原文地址:https://www.cnblogs.com/casperwin/p/13760993.html
Copyright © 2011-2022 走看看