LeetCode: Word Ladder II

看了别人的答案,这题的关键在于数据结构的选择,一开始选择的multimap肯定MLE

 1 class Solution {
 2 public:
 3     void getPath(vector<vector<string> > &ansSet, vector<string> &ans, int now, vector<vector<int> > &pa, vector<string> &que)
 4     {
 5         if (now == -1) 
 6         {
 7             ansSet.push_back(vector<string>(0));
 8             for (int i = ans.size() - 1; i >= 0; i--)
 9                 ansSet.back().push_back(ans[i]);
10             return;
11         }
12         for (int i = 0; i < pa[now].size(); i++)
13         {
14             ans.push_back(que[now]);
15             getPath(ansSet, ans, pa[now][i], pa, que);
16             ans.pop_back();
17         }
18         
19     }
20     vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
21         // Start typing your C/C++ solution below
22         // DO NOT write int main() function
23         vector<string> que;
24         vector<int> step;
25         vector<vector<int> > pa;
26         unordered_map<string, int> hash;
27         step.push_back(1);
28         que.push_back(start);
29         pa.push_back(vector<int>(0));
30         pa.back().push_back(-1);
31         int head = 0;
32         int bestStep = -1;
33         vector<vector<string> > ans;
34         while (head < que.size())
35         {
36             string now = que[head];
37             int nowStep = step[head];
38             if (bestStep > -1 && nowStep == bestStep) break;
39             for (int i = 0; i < now.size(); i++)
40                 for (char ch = 'a'; ch <= 'z'; ch++)
41                 {
42                     string next = now;
43                     if (next[i] == ch) continue;
44                     next[i] = ch;
45                     if (next == end)
46                     {
47                         bestStep = nowStep + 1;
48                         vector<string> single(0);
49                         single.push_back(end);
50                         getPath(ans, single, head, pa, que);
51                     } else if (dict.count(next))
52                     {
53                         if (hash[next] == 0)
54                         {
55                             que.push_back(next);
56                             step.push_back(nowStep + 1);
57                             pa.push_back(vector<int>(0));
58                             pa.back().push_back(head);
59                             hash[next] = pa.size() - 1;
60                         } else if (step[hash[next]] == nowStep + 1)
61                         {
62                             pa[hash[next]].push_back(head);
63                         }
64                     }
65                 }
66             head++;
67         }
68         return ans;
69     }
70 };
原文地址:https://www.cnblogs.com/yingzhongwen/p/3092641.html