90.子集II
0. 记得nums数组一定要先排序!!!!
1. 关键在去重
2. 有重复元素的一定要想到排序!
3. 每一个节点都是我们要收集的结果
class Solution(object):
def backtracking(self,nums,startindex,path,result,used):
# collect the result
result.append(path[:])
# each level recursion
for i in range(startindex,len(nums)):
if i > 0 and nums[i] == nums[i-1] and used[i-1] == False:
continue
# add element to path list
path.append(nums[i])
used[i] = 1
# recursion
self.backtracking(nums,i+1,path,result,used)
# backtracking
path.pop()
used[i] = 0
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
used = [0] * len(nums)
result = []
self.backtracking(nums,0,[],result,used)
return result
491.递增子序
1. 误区:
1. 这道题是不能排序的
2. 4767这个集合取数
1. 先取4,剩余从767这里取
2. 取7,剩余从67这个取
3. 如果当前元素小于,数组里面右边的那个元素就不能取
4. 以此类推,直到不符合递增子序列
3. 叶子节点返回结果,树层不能重复
4. 子集类问题可以不用写终止条件
1. 因为startindex是不断递增,当starindex大于等于数组的时候for循环就不会执行也就没有递归了
class Solution(object):
def backtracking(self,nums,startindex,path,result):
# collect the result set
if(len(path) > 1):
result.append(path[:])
# create a set to store the number we used in this level
uset = set()
# get each number
for i in range(startindex,len(nums)):
if (path and nums[i] < path[-1]) or nums[i] in uset:
# we can skip this tree level, since we already have it
continue
# add element
path.append(nums[i])
uset.add(nums[i])
# recursion
self.backtracking(nums,i+1,path,result)
# backtracking
path.pop()
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
self.backtracking(nums,0,[],result)
return result
46.全排序
1. 排列时强调元素顺序的
2. 使用used数组标记那个元素使用过了
class Solution(object):
def backtracking(self,nums,path,result,used):
# recursion stop condition
if len(path) == len(nums):
result.append(path[:])
return
# logic for each recurion level
for i in range(len(nums)):
if used[i] == 1:
# we just used this number,skip it
continue
# add number
path.append(nums[i])
used[i] = 1
# recursion
self.backtracking(nums,path,result,used)
# backtrack
path.pop()
used[i] = 0
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
used = [0] * len(nums)
self.backtracking(nums,[],result,used)
return result