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

LeetCode 46: Permutations

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

基本資料
#

難易度: medium 第一次嘗試:2022-10-21

  • 提交紀錄:Accepted → Memory Limit Exceeded → Runtime Error → Wrong Answer → Accepted ×2 → Wrong Answer → Runtime Error → Accepted → Runtime Error → Wrong Answer → Accepted

解題思路
#

排列看順序,每一層都可以選任何一個還沒用過的數(Backtracking 模板)。用 used[i] 標記,選之前檢查、回溯時取消標記。path 長度等於 n 時記錄一份複製。

我的嘗試
#

這題提交了 12 次,第一次就 AC 了(用「過濾掉跟目前值相同的數」的寫法),之後每次重寫都錯在小地方:

  • 括號沒寫完、把 index i 而不是值 nums[i] 放進答案([3] 回傳 [[0]])。
  • 忘了呼叫 dfs 或忘了 return、把答案多包了一層 list([[[3]]])。

正確解法
#

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res, path = [], []
        used = [False] * len(nums)
        def dfs():
            if len(path) == len(nums):
                res.append(path[:])
                return
            for i, x in enumerate(nums):
                if used[i]:
                    continue
                used[i] = True
                path.append(x)
                dfs()
                path.pop()
                used[i] = False
        dfs()
        return res

複雜度
#

時間 O(n · n!),空間 O(n)(不算輸出)。

要特別避免的錯誤
#

  • 放進 path 的是值 nums[i],不是 index i。
  • 用 j != i 過濾掉用過的「值」,只在沒有重複時才對;用 index 標記比較安全。

面試口說整理
#

排列看順序,每一層可以選任何一個還沒用過的數,我用 used 陣列標記,選完遞迴再取消標記,path 滿了就記錄一份。時間 O(n · n!)。

相關文章

LeetCode 39: Combination Sum
·1 分鐘
LeetCode Medium Array Backtracking
LeetCode 39 解題筆記:同一個數可以重複選,所以遞迴時下一層從 i 開始(不是 i + 1),這樣也避免了順序不同的重複
LeetCode 40: Combination Sum II
·1 分鐘
LeetCode Medium Array Backtracking
LeetCode 40 解題筆記:每個數只能用一次而且有重複,排序後下一層從 i + 1 開始,同一層跳過跟前一個相同的值
LeetCode 31: Next Permutation
·1 分鐘
LeetCode Medium Array Two-Pointers
LeetCode 31 解題筆記:從右邊找第一個下降的位置 i,跟右邊比它大的最小值交換,再把 i 之後反轉;比較時要包含等於
LeetCode 33: Search in Rotated Sorted Array
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 33 解題筆記:旋轉後 mid 的左右一定有一邊是排序好的,判斷目標在不在那一邊,在就往那邊找,不在就去另一邊
LeetCode 34: Find First and Last Position of Element in Sorted Array
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 34 解題筆記:做兩次 lower bound:第一個 >= target 的位置,以及第一個 >= target + 1 的位置減一
LeetCode 36: Valid Sudoku
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 解題筆記:每個數字在列、欄、3 × 3 宮格各只能出現一次;用 (數字, 列)、(數字, 欄)、(數字, 宮格) 當 key 放進同一個集合