算法题day30(补5.17日卡)

一、刷题

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值