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

LeetCode 3513: Number of Unique XOR Triplets I

·1 分鐘· ·
LeetCode Biweekly-Contest Medium Bit-Manipulation Unsolved
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄
LeetCode Bi-Weekly Contest 154 - 本文屬於一個選集。
§ 2: 本文

基本資料
#

難易度: medium 第一次嘗試: 2025-04-12

  • 總花費時間:20:00.00 (TLE)

解題思路
#

我最初的想法是使用三層 for 迴圈(O(n^3))來遍歷 nums 中所有可能的組合,並將每組的 XOR 結果存入一個名為 seen 的集合中。然而,這種作法顯然會因為三層巢狀迴圈而導致 TLE(Time Limit Exceeded,超出時間限制)。

接著,我嘗試套用 Digit DP,認為可以藉由減少重複計算來優化效能。例如:

  • (0, 0, 0) → 3 XOR 3 XOR 3 = 3
  • (0, 0, 1) → 3 XOR 3 XOR 1 = 1
  • (0, 0, 2) → 3 XOR 3 XOR 2 = 2
  • (0, 1, 2) → 3 XOR 1 XOR 2 = 0

像是 3 XOR 3 這樣的表達式,如果已經計算過並被 lru_cache 快取,就不需要重複計算。

但問題在於,和多數經典 Digit DP 題目中「結果空間相對較小」不同,本題的 XOR 結果集合範圍非常大。因此,lru_cache 的命中率會很低,導致效能提升有限,最終仍然會遇到 TLE。

我認為這題唯一可行的作法可能是透過位元運算(bit manipulation),但我目前仍未找到明確的說明或最佳解法。

解法
#

class Solution:
    def uniqueXorTriplets(self, nums: List[int]) -> int:
        
        from functools import lru_cache

        n = len(nums)

        @lru_cache(None)
        def dfs(position, num_index, xor_result):
            if position == 3:
                return {xor_result}

            result = set()
            for idx in range(num_index, n):
                result.update(
                    dfs(
                        position + 1,
                        idx,
                        xor_result ^ nums[idx]
                    )
                )

            return result

        return len(dfs(0, 0, 0))

收穫
#

  1. 可能的 xor_result 結果集合太大,導致在這種作法下快取命中率非常低,最終會造成 TLE(Time Limit Exceeded)。

遇到的問題
#

LeetCode Bi-Weekly Contest 154 - 本文屬於一個選集。
§ 2: 本文

相關文章

LeetCode 222: Count Complete Tree Nodes
·1 分鐘
LeetCode Medium Binary-Search Bit-Manipulation Tree Binary-Tree
LeetCode 222 解題筆記:完全二元樹,左右兩邊的最左高度相同代表那一邊是滿的,直接用 2^h - 1;O(log² n)
LeetCode 397: Integer Replacement
·1 分鐘
LeetCode Medium Dynamic-Programming Greedy Bit-Manipulation Memoization
LeetCode 397 解題筆記:偶數一定除以 2;奇數選 +1 或 -1,用記憶化遞迴;n 很大不能開 n 大小的陣列
LeetCode 473: Matchsticks to Square
·1 分鐘
LeetCode Medium Array Dynamic-Programming Backtracking Bit-Manipulation
LeetCode 473 解題筆記:總和要能被 4 整除;由大到小把每根火柴放進四個邊之一,超過邊長或跟前一個邊長度相同就跳過
LeetCode 187: Repeated DNA Sequences
·1 分鐘
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 解題筆記:把每個長度 10 的子字串丟進雜湊表計數,出現超過一次的就是答案
LeetCode 137: Single Number II
·1 分鐘
LeetCode Medium Array Bit-Manipulation
LeetCode 137 解題筆記:其他數都出現三次,逐位元統計 1 的個數取 mod 3,剩下的位元就是答案;注意負數
LeetCode 287: Find the Duplicate Number
·1 分鐘
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 解題筆記:把 i -> nums[i] 看成鏈結串列,重複的值就是環的入口,用 Floyd 判圈;O(1) 空間、不改陣列