递归+交换
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
self.count = 0
res = []
end = len(nums)
self.exchange(nums,0,end,res)
return res
def exchange(self,nums,begin,nums_length,res):
if begin == nums_length-1:
self.count += 1
res.append(nums[:])
print('count{0}:{1}'.format(self.count,nums[:]))
for i in range(begin,nums_length):
nums[i],nums[begin] = nums[begin],nums[i]
self.exchange(nums,begin+1,nums_length,res)
nums[i],nums[begin] = nums[begin],nums[i]
递归+跳过已选数字
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
if not nums: return []
if len(nums)==1: return [nums]
for i in range(len(nums)):
for j in self.permute(nums[:i]+nums[i+1:]): #跳过了已选数字
res.append([nums[i]]+j)
return res
第一种方法的图解,有空补