思路:树的层次遍历,BFS,注意这里如果用bool数组标记该字符串是否加入过序列,肯定会超时,因为每次都要遍历整个wordList,所以,建议将加入序列的字符串从wordList中删除,勉强过关;DFS+回溯肯定超时,不用想;
借用评论:
优先广度、深度搜索,最下策再回溯法,因为回溯会有很多问题;
滑动窗口、双指针、dfs/bfs、动态规划、回溯,以后就按照这个顺序思考问题;
动态规划比较难想;
class Solution
{
public:
bool check(string a, string b)
{
bool flag = true;
int len = a.size();
for (int i = 0; i < len; i++)
{
if (!flag && a[i] != b[i])
{
return false;
}
if (a[i] != b[i])
{
flag = false;
}
}
return true;
}
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
int len2 = wordList.size();
if (len2 == 0)
{
return 0;
}
int count = 1;
queue<string> q;
q.push(beginWord);
while (!q.empty())
{
int q_len = q.size();
count++;
while (q_len--)
{
string now = q.front();
q.pop();
for (int i = 0; i < wordList.size(); i++)
{
if (check(now, wordList[i]))
{
if (wordList[i] == endWord)
{
return count;
}
q.push(wordList[i]);
wordList.erase(wordList.begin() + i);
i--;
}
}
}
}
return 0;
}
};