leetcode46
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解法1:
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
# middle = []
def backtrack(nums, middle):
if not nums:
result.append(middle)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i+1:], middle + [nums[i]])
backtrack(nums,[])
return result
解法2:
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def backtrack(first = 0):
# if all integers are used up
if first == n:
output.append(nums[:])
for i in range(first, n):
# place i-th integer first
# in the current permutation
nums[first], nums[i] = nums[i], nums[first]
# use next integers to complete the permutations
backtrack(first + 1)
# backtrack
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output
leetcode 47. 全排列 II
难度中等247
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ]
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result=[]
def trace_back(nums,midle=[]):
if nums==[]:
result.append(midle)
return []
else:
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]:
continue
trace_back(nums[:i]+nums[i+1:],midle+[nums[i]])
trace_back(nums)
return result