题目大意:
给一个开始单词beginword和一个结束单词endword, 再给一个单词列表wordList。从beginword变换到endword, 每次只能变换一个字母,且变换成的词属于wordList。
解决思路:
其实是个变相的BFS,寻找当前集合中相邻的可以进行变换的单词,更新当前集合,直到集合中出现endword。
另,一开始用DFS,递归解法,结果TLE。
超时解法:
var isExist = false var minLen = 0 var target = "" func ladderLength(beginWord string, endWord string, wordList []string) int { minLen = len(wordList) target = endWord bfs(1, beginWord, wordList) if isExist == false { minLen = 0 } return minLen } func bfs(curLen int, curStr string, remainList []string) { for i, remainStr := range remainList { diffNum := 0 for j, curCh := range curStr { if byte(curCh) != byte(remainStr[j]) { diffNum++ } if diffNum > 1 { break } } if target == curStr { isExist = true if minLen > curLen { minLen = curLen return } } if diffNum == 1 { bfs(curLen + 1, remainStr, append(remainList[:i], remainList[i+1:]...)) } } }
原文:https://www.cnblogs.com/AndrewGhost/p/11878335.html