↓快轉到主要內容
  1. LeetCode/

LeetCode 3799: Word Squares II

·1 分鐘· ·
LeetCode Medium Backtracking Enumeration String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-01-04

  • 提交紀錄:Accepted(一次通過)

解題思路
#

四個不同的單字分別當作上、左、右、下四條邊,要滿足四個角的字母相同:

top[0] == left[0]      top[3] == right[0]
bottom[0] == left[3]   bottom[3] == right[3]

依序決定 top → left → right → bottom,每決定一個就檢查跟已經決定的單字有沒有衝突,不符合就不往下一層。

輸出要依 (top, left, right, bottom) 的字典序排序:先把單字排序,四層迴圈依序枚舉,產生的順序就已經是字典序。

我的解法
#

class Solution:
    def wordSquares(self, words: List[str]) -> List[List[str]]:
        words.sort()
        res = []
        for top in words:
            for left in words:
                if left == top or left[0] != top[0]:
                    continue
                for right in words:
                    if right in (top, left) or right[0] != top[3]:
                        continue
                    for bottom in words:
                        if bottom in (top, left, right):
                            continue
                        if bottom[0] == left[3] and bottom[3] == right[3]:
                            res.append([top, left, right, bottom])
        return res

原本交的版本在第二層迴圈裡留了一行 print([word1, word2]),雖然 AC,但大量輸出會拖慢速度,應該刪掉。

可以再快:依首字母分組
#

每一層要找「首字母是某個字母的單字」,可以先建 by_first[c] = 以 c 開頭的單字,內層只掃那一組,不用掃全部的單字。

複雜度
#

最壞 O(n^4),但角落字母的限制讓實際搜尋的組合少很多。

要特別避免的錯誤
#

  • 沒有檢查四個單字互不相同。
  • 先把結果收集起來再排序也可以,但先排序單字就不需要。
  • 留下除錯用的 print。

面試口說整理
#

我依序決定上、左、右、下四個單字,每決定一個就檢查它和已經選的單字在角落的字母是否一致、而且不能重複,不符合就不往下。因為先把單字排序,四層依序枚舉產生的結果自然就是要求的字典序。可以再用首字母分組,讓每一層只看可能的候選。

相關文章

LeetCode 988: Smallest String Starting From Leaf
·1 分鐘
LeetCode Medium String Backtracking Tree Depth-First-Search
LeetCode 988 解題筆記:DFS 時把字元加在字串前面,到葉子時就是「從葉子到根」的字串,取最小的
LeetCode 2044: Count Number of Maximum Bitwise-OR Subsets
·2 分鐘
LeetCode Medium Backtracking Bit-Manipulation Enumeration
LeetCode 2044 解題筆記:最大 OR 就是全部 OR 起來;回溯時一旦達到最大值,剩下的直接算 2^k
LeetCode 93: Restore IP Addresses
·1 分鐘
LeetCode Medium String Backtracking
LeetCode 93 解題筆記:切成剛好 4 段,每段長度 1 到 3、值在 0 到 255、除了 0 本身不能有前導零
LeetCode 131: Palindrome Partitioning
·1 分鐘
LeetCode Medium String Dynamic-Programming Backtracking
LeetCode 131 解題筆記:每一層從剩下字串的開頭切出一段回文,切的長度從 1 到整段都要試
LeetCode 79: Word Search
·2 分鐘
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 解題筆記:從每一格開始回溯,往四個方向比對下一個字元,走過的格子暫時標記,回溯時還原;先用字元次數剪枝
LeetCode 17: Letter Combinations of a Phone Number
·1 分鐘
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 解題筆記:每一層處理一個數字,枚舉它對應的字母;空字串要回傳空 list