详细思路
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>>ans; queue<vector<string>>container; container.push({beginWord}); while(!container.empty()){ unordered_set<string>hadTry; for(int i=container.size();i>0;i--){ vector<string>curArr=container.front();container.pop(); string tail=curArr.back(); if(tail==endWord){ ans.push_back(curArr); continue; } for(int j=0;j<tail.size();j++){ char tmp=tail[j];//要 for(char c=‘a‘;c<=‘z‘;c++){ if(c==tmp)continue;//原始状态 tail[j]=c; if(!dict.count(tail))continue;//不可 hadTry.insert(tail);//记录,之后可删除剪枝 curArr.push_back(tail);//要 container.push(curArr);//要 curArr.pop_back();//不要 } tail[j]=tmp;//不要 } } if(ans.size())return ans;//当前层完 for(auto &s:hadTry)dict.erase(s); } return {}; } };
原文:https://www.cnblogs.com/zhouzihong/p/15092286.html