class Solution:
"""
@param: words: a set of words without duplicates
@return: all word squares
"""
def wordSquares(self, words):
if len(words) == 0:
return []
# write your code here
# pre = set()
pre = collections.defaultdict(set)
n = len(words)
m = len(words[0])
for word in words:
for i in range(m):
pre[word[:i]].add(word)
ans = []
def search(word, line, matrix, has):
# has.add(word)
if len(matrix) == m:
ans.append(matrix[:])
else:
prefix = "".join([matrix[i][line] for i in range(line)])
for tar in pre[prefix]:
if tar not in has:
matrix.append(tar)
has.add(tar)
search(tar, line + 1, matrix, has)
has.remove(tar)
matrix.pop()
for word in words:
has = set([word])
search(word, 1, [word], has)
return ans
dfs 搜索
最新推荐文章于 2023-08-11 23:14:48 发布