首页 > 其他 > 详细

[leetcode]Word Squares

时间:2020-02-05 23:36:58      阅读:76      评论:0      收藏:0      [点我收藏+]

DFS搜索,使用prefix的字典加速;另外注意往result里放时要square.copy()一下

class Solution:
    def wordSquares(self, words: List[str]) -> List[List[str]]:
        wordsDict = {}
        
        for i in range(len(words)):
            word = words[i]
            for k in range(len(word)):
                if word[0:k+1] not in wordsDict:
                    wordsDict[word[0:k+1]] = []
                wordsDict[word[0:k+1]].append(word)
            
        result = []
        
        # backtrace
        for i in range(len(words)):
            self.backtrace([words[i]], result, words, wordsDict)
            
        return result
        
    def backtrace(self, square, result, words, wordsDict):
        n = len(words[0])
        i = len(square) - 1 # idx for newly add line
        for k in range(0, i):
            if square[i][k] != square[k][i]:
                # check fail, return
                return
        
        if i + 1 == n: # square is good
            result.append(square.copy())
            return
        
        prefix = ‘‘
        for k in range(0, i+1):
            prefix += square[k][i+1]

        if prefix not in wordsDict:
            return
        
        for word in wordsDict[prefix]:
            square.append(word)
            self.backtrace(square, result, words, wordsDict)
            square.pop()

  

[leetcode]Word Squares

原文:https://www.cnblogs.com/lautsie/p/12267161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!