【leetcode刷刷】491.递增子序列、46.全排列、47.全排列 II

491.递增子序列

  1. 使用一个set来记录每层的元素是否使用了,使用过的就不能用。不能采用之前去重方法的原因是,不能改变原始数组的顺序
class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        self.res = []
        self.backtracking(nums, 0, [])
        return self.res

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

        uset = set() # # 使用集合对本层元素进行去重
        for i in range(start_index, len(nums)):
            if (i > start_index and nums[i] == nums[i-1]) or nums[i] in uset: continue
            if len(path) == 0 or (len(path) > 0 and nums[i] >= path[-1]):
                uset.add(nums[i])  # 记录这个元素在本层用过了,本层后面不能再用了
                path.append(nums[i])
                self.backtracking(nums, i+1, path)
                path.pop()

46.全排列

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

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

47.全排列 II

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

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

你可能感兴趣的:(leetcode,算法,职场和发展)