491.递增子序列
本题求自增子序列,是不能对原数组进行排序的,排完序的数组都是自增子序列了。
class Solution:#l利用set去重
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
result=[]
path=[]
self.backtracking(nums,0,path,result)
return result
def backtracking(self,nums,startIndex,path,result):
if len(path)>1:
result.append(path[:])#注意要使用切片将当前路径的副本加入结果集
#不加return
uset=set()
for i in range(startIndex,len(nums)):
if (path and nums[i]<path[-1]) or nums[i] in uset:
continue
uset.add(nums[i])#只记录本层元素是否重复使用,新的一层会重新定义
path.append(nums[i])
self.backtracking(nums,i+1,path,result)
path.pop()
class Solution:#利用哈希表去重
def findSubsequences(self,nums):
result=[]
path=[]
self.backtracking(nums,0,path,result)
return result
def backtracking(self,nums,startIndex,path,result):
if len(path)>1:
result.append(path[:])
used=[0]*201 # 使用数组来进行去重操作,题目说数值范围[-100, 100]
for i in range(startIndex,len(nums)):
if(path and nums[i]<path[-1]) or used[nums[i]+100]==1:
continue
used[nums[i]+100]=1
path.append(nums[i])
self.backtracking(nums,i+1,path,result)
path.pop()
46.全排列
首先排列是有序的,也就是说 [1,2] 和 [2,1] 是两个集合,这和之前分析的子集以及组合所不同的地方。
不用startIndex因为每次都要从头开始搜索
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result=[]
used=[False]*len(nums)
self.backtracking(nums,[],used,result)
return result
def backtracking(self,nums,path,used,result):
if len(nums)==len(path):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i]=True
path.append(nums[i])
self.backtracking(nums,path,used,result)
path.pop()
used[i]=False
47.全排列II
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result=[]
self.backtracking(nums,[],[False]*len(nums),result)
return result
def backtracking(self,nums,path,used,result):
if len(path)==len(nums):
result.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,used,result)
used[i]=False
path.pop()