491.非递减子序列
力扣链接
给你一个整数数组 nums ,找出并返回所有该数组中不同的非递减子序列,至少有两个元素 。你可以按 任意顺序 返回答案。
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
self.backtracking(nums, 0, path, res)
return res
def backtracking(self, nums, startIndex, path, res):
if len(path)>1:
res.append(path[:])
uset = set() # 本层元素去重
for i in range(startIndex, len(nums)):
if nums[i] in uset or (path and nums[i] < path[-1]): # 如果 用过了 或 递减 则跳过
continue
uset.add(nums[i]) # 记录用过了
path.append(nums[i])
self.backtracking(nums, i+1, path, res)
path.pop()
46.全排列
力扣链接
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
used = [False]*len(nums)
self.backtracking(nums, path, res, used)
return res
def backtracking(self, nums, path, res, used): # 不需要startIndex
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i] == True:
continue
used[i] = True #标记用过了
path.append(nums[i])
self.backtracking(nums, path, res, used)
path.pop()# 回溯
used[i] = False
全排列 II
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
used = [False] * len(nums)
nums.sort()
self.backtracking(nums, path, res, used)
return res
def backtracking(self, nums, path, res, used):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1] and used[i-1]==False:
continue
if used[i] == False:
used[i]=True
path.append(nums[i])
self.backtracking(nums, path, res, used)
path.pop()# 回溯
used[i]=False