Open azl397985856 opened 3 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
''' 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)
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
47 全排列 II
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/permutations-ii/
前置知识
题目描述
示例:
输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1]