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;
        }
    };
    
  • 相关阅读:
    康托(逆)展开(2015.8.6)
    高精度计算(2015.8.1)
    笔记(2015.8.1)
    筛法求素数(2015.7.30)
    欧几里德算法(2015.7.28)
    快速幂取模(2015.7.29)
    同余
    图论相关算法
    笔记(2015-07-24)
    ACM进阶计划
  • 原文地址:https://www.cnblogs.com/casperwin/p/13760993.html
Copyright © 2011-2022 走看看