思路:BFS+DFS
首先和Word Ladder一样,先BFS构建一个梯子,例如,用string_map将[“hot”,“dot”,“dog”,“lot”,“log”,“cog”]映射为1,2,3,2,3,4
然后用DFS从endWord开始往回构建vector对象,像下楼梯一样一步一步走回来4->3->2->1

看了题解,不然我连第一题都不会的哈哈

class Solution {
public:
vector<vector<string>>res;
void dfs(vector<string>temp_res,string str,string beginWord,unordered_map<string,int>string_map){
int next_position=string_map[str]-1;
for(int i=0;i<beginWord.length();++i){
string current=str;
for(char ch='a';ch<='z';++ch){
current[i]=ch;
if(current==str)continue;
if(string_map[current]==next_position){
temp_res.push_back(current);
if(current==beginWord){
reverse(temp_res.begin(),temp_res.end());
res.push_back(temp_res);
return;
}
dfs(temp_res,current,beginWord,string_map);
temp_res.pop_back();
}
}
}
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string>string_set(wordList.begin(),wordList.end());
if(!string_set.count(endWord))return res;
unordered_map<string,int>string_map{{beginWord,1}};
queue<string>q;
q.push(beginWord);
//bfs
int end_position=INT_MAX;
while(!q.empty()){
string front_string=q.front();
if(string_map[front_string]>=end_position)break;
q.pop();
for(int i=0;i<beginWord.length();++i){
string current=front_string;
for(char ch='a';ch<='z';++ch){
current[i]=ch;

if(current==front_string)continue;
if(current==endWord)end_position=string_map[current]+1;
if(string_set.count(current)&&string_map[current]==0){
q.push(current);
string_map[current]=string_map[front_string]+1;
}

}
}
}
//dfs
vector<string>temp_res;
temp_res.push_back(endWord);
dfs(temp_res,endWord,beginWord,string_map);
return res;
}
};