leetcode 46. 全排列

https://leetcode-cn.com/probl...python

簡單的深度優先遍歷。app

嘗試了 list 的 append 再 pop 和直接使用下標修改 list 的值。code

看起來對結果影響很小。內存

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ans = []
        n = len(nums)
        f = [False] * n
        l = []
        def dfs(i):
            if i == n:
                ans.append(l[::])
                return
            for j in range(n):
                if not f[j]:
                    l.append(nums[j])
                    f[j] = True
                    dfs(i+1)
                    f[j] = False
                    l.pop()
        dfs(0)
        return ans

執行用時 :40 ms, 在全部Python3提交中擊敗了88.14%的用戶leetcode

內存消耗 :13.1 MB, 在全部Python3提交中擊敗了59.71%的用戶get

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        ans = []
        n = len(nums)
        f = [False] * n
        l = [0] * n
        def dfs(i):
            if i == n:
                ans.append(l[::])
                return
            for j in range(n):
                if not f[j]:
                    l[i] = nums[j]
                    f[j] = True
                    dfs(i+1)
                    f[j] = False

        dfs(0)
        return ans

執行用時 :40 ms, 在全部Python3提交中擊敗了88.14%的用戶博客

內存消耗 :13.1 MB, 在全部Python3提交中擊敗了59.50%的用戶io

歡迎來個人博客: https://codeplot.top/
個人博客刷題分類:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/class

相關文章
相關標籤/搜索