代码随想录算法训练营Day29 | 回溯算法(5/6) LeetCode 491.递增子序列 46.全排列 47.全排列 II

本文介绍了如何使用回溯法解决编程问题,分别针对不降序子序列(Non-decreasingSubsequences)、不允许重复的排列(PermutationsII)以及处理重复元素的独特排列(Permutations)。通过示例展示了如何在回溯过程中处理排序、剪枝和避免重复的结果。

第一题

491. Non-decreasing Subsequences

Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.

这道题和LC 90有点像,但是这道题在求子集之前不可以先进行排序,不然会影响求出来的子集。

class Solution:
    def findSubsequences(self, nums):
        result = []
        path = []
        self.backtracking(nums, 0, path, result)
        return result
    
    def backtracking(self, nums, startIndex, path, result):
        if len(path) > 1:
            result.append(path[:]) 
        uset = set()  
        for i in range(startIndex, len(nums)):
            if (path and nums[i] < path[-1]) or nums[i] in uset:
                continue
            
            uset.add(nums[i])  
            path.append(nums[i])
            self.backtracking(nums, i + 1, path, result)
            path.pop()

第二题

46. Permutations

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

因为组合是有序的,比如[1,2] 和 [2,1]是两个集合,因此不能使用原来的startindex来控制删去重复部分了,相反,可以用一个used来标识哪些是重复出现的元素。

class Solution:
    def permute(self, nums):
        result = []
        self.backtracking(nums, [], [False] * len(nums), result)
        return result

    def backtracking(self, nums, path, used, result):
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            used[i] = True
            path.append(nums[i])
            self.backtracking(nums, path, used, result)
            path.pop()
            used[i] = False

第三题

47. Permutations II

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

这道题改成了nums包含重复元素,但是排列的结果不能有重复,这就又涉及到了剪枝操作。

class Solution:
    def permuteUnique(self, nums):
        nums.sort()  
        result = []
        self.backtracking(nums, [], [False] * len(nums), result)
        return result

    def backtracking(self, nums, path, used, result):
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]) or used[i]:
                continue
            used[i] = True
            path.append(nums[i])
            self.backtracking(nums, path, used, result)
            path.pop()
            used[i] = False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值