491.递增子序列
给你一个整数数组 nums
,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res = []
self.backstacking(nums, 0, [], res)
return res
def backstacking(self, nums, startIndex, curPath, res):
if curPath not in res and len(curPath) > 1:
if curPath[-2] <= curPath[-1]:
res.append(curPath[:])
else:return
for i in range(startIndex, len(nums)):
curPath.append(nums[i])
self.backstacking(nums, i+1, curPath, res)
curPath.pop()
46.全排列
给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
used = [False] * len(nums)
self.backstacking(nums, 0, [], res, used, 0)
return res
def backstacking(self, nums, startIndex, curPath, res, used, curLength):
if len(nums) == curLength:
res.append(curPath[:])
return
for i in range(startIndex, len(nums)):
if not used[i]:
used[i] = True
curPath.append(nums[i])
self.backstacking(nums, 0, curPath, res, used, curLength+1)
used[i] = False
curPath.pop()
47.全排列 II
给定一个可包含重复数字的序列 nums
,按任意顺序 返回所有不重复的全排列。
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res = []
used = [False] * len(nums)
self.backstracking(nums, 0, [], res, used, 0)
return res
def backstracking(self, nums, startIndex, curPath, res, used, curLength):
if len(nums) == curLength and curPath not in res:
res.append(curPath[:])
return
for i in range(startIndex, len(nums)):
if not used[i]:
used[i] = True
curPath.append(nums[i])
self.backstracking(nums, 0, curPath, res, used, curLength+1)
used[i] = False
curPath.pop()