代码随想录算法训练营第28天 | 回溯4:491.递增子序列、46.全排列、47.全排列 II
491.递增子序列
https://leetcode.cn/problems/non-decreasing-subsequences/
代码随想录
https://programmercarl.com/0491.递增子序列.html#算法公开课
46.全排列
https://leetcode.cn/problems/permutations/description/
代码随想录
https://programmercarl.com/0046.全排列.html
47.全排列 II
https://leetcode.cn/problems/permutations-ii/description/
代码随想录
https://programmercarl.com/0047.全排列II.html#算法公开课
491.递增子序列
题解思路
- 停止条件:
- 个数大于2个 并不重复;
- index到最后时;
- 控制递增:在循环内控制下一个元素;
- 剪枝:相同元素不遍历
- 去重:
- set去重
题解代码
class Solution:
def __init__(self):
self.res = []
self.path = []
def back_trace(self,nums,index):
if len(self.path)>=2:
self.res.append(self.path[:])
if index==len(nums):
return
uset = set()
for i in range(index,len(nums)):
if (len(self.path)>0 and nums[i]<self.path[-1]) or nums[i] in uset:
continue
## 保证本层不重复使用该元素
uset.add(nums[i])
self.path.append(nums[i])
self.back_trace(nums,i+1)
self.path.pop()
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
if len(nums)==0:
return self.res
self.back_trace(nums,0)
return self.res
46.全排列
题解思路
- 排列和分组的区别:需要把所有元素用完;
题解代码
class Solution:
def __init__(self):
self.res = []
self.path = []
def back_trace(self,nums,used):
if len(self.path)==len(nums):
self.res.append(self.path[:])
return
for i in range(len(nums)):
if used[i]==1:
continue
used[i] = 1
self.path.append(nums[i])
self.back_trace(nums,used)
self.path.pop()
used[i] = 0
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums)==0:
return []
self.back_trace(nums,[0]*len(nums))
return self.res
47.全排列 II
题解思路
- 元素重复可以 但是同一树枝不能重复取l used数组解决
class Solution:
def __init__(self):
self.res = []
self.path = []
def back_trace(self,nums,used):
if len(self.path) == len(nums):
self.res.append(self.path[:])
return
for i in range(len(nums)):
if used[i]==1 or (i>0 and nums[i]==nums[i-1] and used[i-1]==0):
##1.一个数组中的数字不能重复取
##2.同一层数重复读取数字
continue
used[i]=1
self.path.append(nums[i])
self.back_trace(nums,used)
self.path.pop()
used[i]=0
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
if len(nums)==0:
return self.res
nums = sorted(nums)
self.back_trace(nums,[0]*len(nums))
return self.res
标签:排列,nums,46,res,self,随想录,len,used,path
From: https://www.cnblogs.com/P201821440041/p/18307876