491. 递增子序列
不能用“找元素递增的子集”的思路
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
path = []
res = []
def recursion(j):
if len(path) > 1:
res.append(path[:])
if j == len(nums):
return
# 创建集合存储
usage_list = set()
for i in range(j, len(nums)):
if nums[i] in usage_list:
continue
if path and path[-1] > nums[i]:
continue
usage_list.add(nums[i])
path.append(nums[i])
recursion(i+1)
path.pop()
recursion(0)
return res
46. 全排列
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
used = [False] * len(nums)
def recursion():
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
path.append(nums[i])
used[i] = True
recursion()
used[i] = False
path.pop()
recursion()
return res
原地交换nums元素的思路
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(first = 0):
# 所有数都填完了
if first == n:
res.append(nums[:])
for i in range(first, n):
# print(first, i, res)
# 动态维护数组
nums[first], nums[i] = nums[i], nums[first]
# 继续递归填下一个数
backtrack(first + 1)
# 撤销操作
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
res = []
backtrack()
return res
47. 全排列 II
注意如何使用的used数组
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
used = [False] * len(nums)
nums.sort()
def recursion():
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if not used[i]:
# 树层上去重的思路
if i>0 and nums[i] == nums[i-1] and not used[i-1]:
continue
path.append(nums[i])
used[i] = True
recursion()
used[i] = False
path.pop()
recursion()
return res