240
笔下虽有千言,胸中实无一策

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;
    }
};
posted @ 2020-10-02 12:55  CasperWin  阅读(62)  评论(0编辑  收藏  举报