1.Word Ladder
问题描述:
给两个word(beginWord和endWord)和一个字典word list,找出从beginWord到endWord之间的长度最长的一个序列,条件:
1.字典中的每个单词只能使用一次;
2.序列中的每个单词都必须是字典中的单词;
例如:
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
注意:
如果找不到合适的序列,返回0;
所有的单词长度都是一样的;
所有的单词都只由小写字母组成。
思路:
采用DFS依次遍历
代码如下:
1 class Solution { 2 public: 3 int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { 4 unordered_set<string> s1 = {beginWord}; // Front end 5 unordered_set<string> s2 = {endWord}; // Back end 6 wordDict.erase(beginWord); 7 wordDict.erase(endWord); 8 9 return ladderLength(s1, s2, wordDict, 1); 10 } 11 12 private: 13 int ladderLength(unordered_set<string>& s1, unordered_set<string>& s2, unordered_set<string>& wordDict, int level) { 14 if (s1.empty()) // We can‘t find one. 15 return 0; 16 unordered_set<string> s3; // s3 stores all words 1 step from s1. 17 for (auto word : s1) { 18 for (auto& ch : word) { 19 auto originalCh = ch; 20 for (ch = ‘a‘; ch <= ‘z‘; ++ ch) { 21 if (ch != originalCh) { 22 if (s2.count(word)) // We found one. 23 return level + 1; 24 if (wordDict.count(word)) { 25 wordDict.erase(word); // Avoid duplicates. 26 s3.insert(word); 27 } 28 } 29 } 30 31 ch = originalCh; 32 } 33 } 34 // Continue with the one with smaller size. 35 return (s2.size() <= s3.size()) ? ladderLength(s2, s3, wordDict, level + 1) : ladderLength(s3, s2, wordDict, level + 1); 36 } 37 };
时间: 2024-11-07 04:02:09