leetcode-pp / 91alg-14-daily-check

0 stars 0 forks source link

【Day 82 】2024-11-04 - 47 全排列 II #88

Open azl397985856 opened 3 weeks ago

azl397985856 commented 3 weeks ago

47 全排列 II

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/permutations-ii/

前置知识

示例:

输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1]

Fightforcoding commented 2 weeks ago

class Solution: # T: O(n n!) S: O(n n!) def permuteUnique(self, nums: List[int]) -> List[List[int]]:

    nums.sort()
    res = []
    def backtrack(pre, arr):
        if len(arr) == 1:
            res.append(pre + arr)
            return             
        for i in range(len(arr)):
            if i - 1 >= 0 and arr[i] == arr[i-1]:
                continue

            backtrack(pre+[arr[i]], arr[:i]+arr[i+1:])

    backtrack([], nums)
    return res
qiaoeve commented 2 weeks ago

''' class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: def dfs(x): if x == len(nums) - 1: res.append(list(nums)) # 添加排列方案 return dic = set() for i in range(x, len(nums)): if nums[i] in dic: continue # 重复,因此剪枝 dic.add(nums[i]) nums[i], nums[x] = nums[x], nums[i] # 交换,将 nums[i] 固定在第 x 位 dfs(x + 1) # 开启固定第 x + 1 位元素 nums[i], nums[x] = nums[x], nums[i] # 恢复交换 res = [] dfs(0) return res ''' 时间复杂度:O(N!N)

huizsh commented 2 weeks ago

class Solution: def backtrack(numbers, pre): nonlocal res if len(numbers) <= 1: res.append(pre + numbers) return for key, value in enumerate(numbers): if value not in numbers[:key]: backtrack(numbers[:key] + numbers[key + 1:], pre+[value])

res = []
if not len(nums): return []
backtrack(nums, [])
return res