代码随想录刷题第二十九天| 491.递增子序列 * 46.全排列 * 47.全排列 II

2023-12-31 05:10:04

代码随想录刷题第二十九天

递增子序列 (LC 491)

题目思路:

在这里插入图片描述

代码实现:

class Solution:
    def __init__(self):
        self.path = []
        self.result = []
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        self.backtracking(nums, 0)
        return self.result

    def backtracking(self, nums, startindex):
        if len(self.path)>1:
            self.result.append(self.path[:])

        uset = []   
        for i in range(startindex, len(nums)):
            if nums[i] in uset or (self.path and nums[i] < self.path[-1]):
                continue
            else:
                uset.append(nums[i])
                self.path.append(nums[i])
                self.backtracking(nums, i+1)
                self.path.pop()

全排列 (LC 46)

题目思路:

在这里插入图片描述

代码实现:

class Solution:
    def __init__(self):
        self.result = []
        self.path = []

    def permute(self, nums: List[int]) -> List[List[int]]:
        used = [0 for _ in range(len(nums))]
        self.backtracking(nums, used)
        return self.result        
        
    def backtracking(self, nums, used):
        if len(self.path) == len(nums):
            self.result.append(self.path[:])
            return

        for i in range(len(nums)):
            if used[i] == 1:
                continue
            used[i] = 1
            self.path.append(nums[i])
            self.backtracking(nums, used)
            self.path.pop()
            used[i] = 0  

全排列II (LC 47)

题目思路:

在这里插入图片描述

代码实现:

class Solution:
    def __init__(self):
        self.result = []
        self.path = []

    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        used = [0 for _ in range(len(nums))]
        nums.sort()
        self.backtracking(nums, used)
        return self.result        
        
    def backtracking(self, nums, used):
        if len(self.path) == len(nums):
            self.result.append(self.path[:])
            return

        for i in range(len(nums)):
            if used[i] == 1:
                continue
            if i>0 and nums[i]==nums[i-1] and used[i-1]==0:
                continue
            used[i] = 1
            self.path.append(nums[i])
            self.backtracking(nums, used)
            self.path.pop()
            used[i] = 0

文章来源:https://blog.csdn.net/shaozi25/article/details/135300976
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。