一、刷题
1.leetcode题目 491. 非递减子序列 - 力扣(LeetCode)
解决:
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
def dfs(nums,path,result,s_index):
if len(path)>=2:
result.append(path[:])
used = set()
for i in range(s_index,len(nums)):
if (not path or nums[i] >= path[-1]) and nums[i] not in used :
used.add(nums[i])
path.append(nums[i])
dfs(nums,path,result,i+1)
path.pop()
dfs(nums,path,result,0)
return result
2.leetcode题目 46. 全排列 - 力扣(LeetCode)
因为每一次横向遍历都需要遍历从一整个nums开始 所以没有Index
还有 需要注意的点是剪枝的时候
解决:
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
used = [False]*len(nums)
def dfs(nums,path,result,used):
if len(path) == len(nums):
result.append(path[:])
for i in range(len(nums)):
if not used[i]:
path.append(nums[i])
used[i] = True
dfs(nums,path,result,used)
used[i] = False
path.pop()
dfs(nums,path,result,used)
return result
3.leetcode题目 47. 全排列 II - 力扣(LeetCode)
注意双重去重
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
label = [False]*len(nums)
def dfs(nums,path,result,label):
if len(path) == len(nums):
result.append(path[:])
return result
used = set()
for i in range(len(nums)):
if i>0 and nums[i] in used:
continue
if not label[i]:
used.add(nums[i])
path.append(nums[i])
label[i] = True
dfs(nums,path,result,label)
label[i] = False
path.pop()
dfs(nums,path,result,label)
return result