【leetcode】126. Word Ladder II

题目如下:

解题思路: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

原文地址:https://www.cnblogs.com/seyjs/p/9556156.html

时间: 2024-10-03 18:43:32

【leetcode】126. Word Ladder II的相关文章

126. Word Ladder II(js)

126. Word Ladder II Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in

【Leetcode】Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? 思路:由[Leetcode]Linked List Cycle可知,利用一快一慢两个指针能够判断出链表是否存在环路.假设两个指针相遇之前slow走了s步,则fast走了2s步,并且fast已经在长度

【LeetCode】Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ lengt

【Leetcode】Pascal&#39;s Triangle II

题目链接:https://leetcode.com/problems/pascals-triangle-ii/ 题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 思路: 要求空间复杂度为O

【leetcode】Pascal&#39;s Triangle II (python)

其实每一行的结果是二项式展开的系数,但是考虑到当给定的参数过大的时候,在求组合的过程中会出现溢出(中间过程要用到乘法),但是这样的算法的时间复杂度是O(N),所以在参数不太大的时候,还是不错的. 这里用迭代的方法来求,当然复杂度就高了,是O(N^2),这里主要说下迭代时候的技巧,即在一个列表(数组)里进行迭代,实现如此的操作,要求在求下一行的时候,要从后往前进行,若是从前向后,就把后面要用的变量给改掉了,产生"脏"数据.从后向前不会(为何?),因为下一行比上一行多一个.(自己写写例子看

【LeetCode】113. Path Sum II 基于Java和C++的解法及分析

113. Path Sum II Total Accepted: 80509 Total Submissions: 284188 Difficulty: Medium Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8

【LeetCode】Single Number I &amp; II

Single Number I : Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 解法不少,贴一种: 1 cla

【LeetCode】House Robber I &amp; II 解题报告

[题目] I You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it wil

【LeetCode】Combination Sum I &amp; II 解题报告

[Combination Sum I] Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (inc