代码随想录算法训练营第二十九天| 491.递增子序列、46.全排列 、47.全排列 II

发布时间:2024年01月16日

代码随想录算法训练营第二十九天| 491.递增子序列、46.全排列 、47.全排列 II

题目

491.递增子序列

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.backstacking(nums, 0, [], res)
        return res
    def backstacking(self, nums, startIndex, curPath, res):
        if curPath not in res and len(curPath) > 1:
            if curPath[-2] <= curPath[-1]:
                res.append(curPath[:])
            else:return 
        for i in range(startIndex, len(nums)):
            curPath.append(nums[i])
            self.backstacking(nums, i+1, curPath, res)
            curPath.pop()

题目

46.全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        used = [False] * len(nums)
        self.backstacking(nums, 0, [], res, used, 0)
        return res
    
    def backstacking(self, nums, startIndex, curPath, res, used, curLength):
        if len(nums) == curLength:
            res.append(curPath[:])
            return
        for i in range(startIndex, len(nums)):
            if not used[i]:
                used[i] = True
                curPath.append(nums[i])
                self.backstacking(nums, 0, curPath, res, used, curLength+1)
                used[i] = False
                curPath.pop()

题目

47.全排列 II

给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        res = []
        used = [False] * len(nums)
        self.backstracking(nums, 0, [], res, used, 0)
        return res

    def backstracking(self, nums, startIndex, curPath, res, used, curLength):
        if len(nums) == curLength and curPath not in res:
            res.append(curPath[:])
            return
        for i in range(startIndex, len(nums)):
            if not used[i]:
                used[i] = True
                curPath.append(nums[i])
                self.backstracking(nums, 0, curPath, res, used, curLength+1)
                used[i] = False
                curPath.pop()
文章来源:https://blog.csdn.net/qq_46528858/article/details/135622138
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。