1. 程式人生 > >【leetcode】126. Word Ladder II

【leetcode】126. Word Ladder II

not dde print add else == rate pop 運算

題目如下:

技術分享圖片

解題思路:DFS或者BFS都行。本題的關鍵在於減少重復計算。我采用了兩種方法:一是用字典dic_ladderlist記錄每一個單詞可以ladder的單詞列表;另外是用dp數組記錄從startword開始到wordlist每一個word的最小轉換次數,這一點非常重要,可以過濾很多無效的運算。

代碼如下:

class Solution(object):
    def getLadderList(self, w,d):
        l = []
        r = []
        for i in xrange(26):
            l.append(chr(i 
+ ord(a))) for i in range(len(w)): for j in l: if w[i] != j: v = w[:i] + j + w[i+1:] if v in d: r.append(v) return r def findLadders(self, beginWord, endWord, wordList): #print len(wordList)
dic = {} for i,v in enumerate(wordList): dic[v] = i if endWord not in dic: return [] queue = [(beginWord,0,beginWord)] res = [] shortest = len(wordList) + 1 dp = [shortest for i in wordList] dic_ladderlist = {}
while len(queue) > 0: word,count,path = queue.pop(0) if count > shortest: continue if word in dic_ladderlist: wl = dic_ladderlist[word] else: wl = self.getLadderList(word,dic) dic_ladderlist[word] = wl for i in wl: if dp[dic[i]] >= count+1 : if i == endWord: #path = path + ‘ ‘ + i pl = path.split( ) pl.append(endWord) if len(pl) < shortest: res = [] res.append(pl) shortest = len(pl) elif len(pl) == shortest: res.append(pl) shortest = len(pl) continue queue.append((i,count + 1,path + + i)) dp[dic[i]] = count + 1 return res

【leetcode】126. Word Ladder II