491.递增子序列
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.11
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/increasing-subsequences/
from typing import List
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
result = []
temp_result = []
def back_tracking(nums: List[int], start_index: int) -> None:
if len(temp_result) > 1:
result.append(temp_result[:])
if start_index == len(nums):
return
# 同一层定义一个set集合
used_list = set()
for i in range(start_index, len(nums)):
if nums[i] in used_list or temp_result and nums[i] < temp_result[-1]:
continue
used_list.add(nums[i])
temp_result.append(nums[i])
back_tracking(nums, i + 1)
temp_result.pop()
back_tracking(nums, 0)
return result
if __name__ == '__main__':
pass
46.全排列
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.11
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/permutations/
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
temp_list = []
used_list = [0] * len(nums)
def back_tracking(nums: List[int]) -> None:
if len(temp_list) == len(nums):
result.append(temp_list[:])
for i in range(len(nums)):
if used_list[i] == 0:
temp_list.append(nums[i])
used_list[i] = 1
back_tracking(nums)
used_list[i] = 0
temp_list.pop()
back_tracking(nums)
return result
if __name__ == '__main__':
nums = [1, 2, 3]
s = Solution()
print(s.permute(nums))
47.全排列 II
代码
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022.11
# @Author : hello algorithm!
# @Note : https://leetcode.cn/problems/permutations-ii/
from typing import List
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
result = []
temp_list = []
# 判断自己本身是否被使用
used_list = [0] * len(nums)
nums.sort()
def back_tracking(nums: List[int]) -> None:
if len(temp_list) == len(nums):
result.append(temp_list[:])
for i in range(len(nums)):
if used_list[i] == 1 or i > 0 and nums[i] == nums[i - 1] and used_list[i - 1] == 0:
continue
temp_list.append(nums[i])
used_list[i] = 1
back_tracking(nums)
used_list[i] = 0
temp_list.pop()
back_tracking(nums)
return result
if __name__ == '__main__':
nums = [1, 1, 2]
s = Solution()
print(s.permuteUnique(nums))