491.递增子序列
LeetCode - The World's Leading Online Programming Learning Platform
视频讲解:回溯算法精讲,树层去重与树枝去重 | LeetCode:491.递增子序列_哔哩哔哩_bilibili
class Solution(object):
#define global variables
def __init__(self):
self.path=[]
self.res = []
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#define backtracking function
def backtracking(nums,start_index):
#collect answers
if len(self.path) >=2:
self.res.append(self.path[:])
#base case
if start_index >= len(nums):
return
#set up a unordered set to check if there is any repeated values
#every recursion cycle
used=set()
#loop for every single layer
for i in range(start_index, len(nums)):
# if the current value is smaller than the previous path
#or it is in the used set, then we skip the value.
if (self.path and self.path[-1]>nums[i]) or nums[i] in used:
continue
#renew used set
used.add(nums[i])
self.path.append(nums[i])
backtracking(nums, i+1)
self.path.pop()
backtracking(nums,0)
return self.res
46.全排列
LeetCode - The World's Leading Online Programming Learning Platform
视频讲解:组合与排列的区别,回溯算法求解的时候,有何不同?| LeetCode:46.全排列_哔哩哔哩_bilibili
class Solution(object):
#set up global variables
def __init__(self):
self.path=[]
self.res=[]
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#base case, collect answers if current path has the same length as nums
if len(self.path)==len(nums):
self.res.append(self.path[:])
return
#loop of recursion for single layer, start over from the first index
#every time
for i in range(len(nums)):
#skip if we have the value collected
if nums[i] in self.path:
continue
self.path.append(nums[i])
self.permute(nums)
#backtracking
self.path.pop()
#return result
return self.res
47.全排列 II
本题 就是我们讲过的 40.组合总和II 去重逻辑 和 46.全排列 的结合,可以先自己做一下,然后重点看一下 文章中 我讲的拓展内容。 used[i - 1] == true 也行,used[i - 1] == false 也行
视频讲解:回溯算法求解全排列,如何去重?| LeetCode:47.全排列 II_哔哩哔哩_bilibili
class Solution(object):
#global variabls
def __init__(self):
self.path=[]
self.res=[]
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
used=[0] * len(nums)
#sort for repeation reletion
nums.sort()
#def backtracking function
def backtracking(nums):
#base case
if len(self.path)==len(nums):
self.res.append(self.path[:])
return
#loop for every single layer
for i in range(len(nums)):
#if current value is not used,we first check if the previous
#number is used and if it is not the first value and if it is
#equal to the previous number
#if all of the answer is yes, we need to skip this layer
#or we can mark this value as used and append it to path
if used[i]==0:
if i>0 and used[i-1]==1 and nums[i]==nums[i-1]:
continue
used[i]=1
self.path.append(nums[i])
#recursion
backtracking(nums)
#backtracking
self.path.pop()
used[i]=0
backtracking(nums)
return self.res