425. Word Squares

https://leetcode.com/problems/word-squares/

Given a set of words (without duplicates), find all word squares you can build from them.

A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.

b a l l
a r e a
l e a d
l a d y

Note:

  1. There are at least 1 and at most 1000 words.

  2. All words will have the exact same length.

  3. Word length is at least 1 and at most 5.

  4. Each word contains only lowercase English alphabet a-z.

Example 1:

Input:
["area","lead","wall","lady","ball"]

Output:
[
  [ "wall",
    "area",
    "lead",
    "lady"
  ],
  [ "ball",
    "area",
    "lead",
    "lady"
  ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).

Example 2:

给无重复且等长的一堆字符串,让返回它们能形成的所有word square,word sqaure是由等长字符串组成的矩阵,要求相同编号的行和列字符串也相同。返回所有=>DFS。DFS时不断往下遍历行,在新的一行里需要找满足根据前面行生成的已有前缀下的字符串作为候选。找满足前缀的字符串=> trie。类似design autocomplete把每个trie上的前缀节点后面所接的单词存在该结点,用于方便在DFS时找候选。

参考了

Last updated

Was this helpful?