- 题目:将给定的无重复的数组全排列
def permute(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def permutations(nums, start, ret):
if start >= len(nums): # 满足条件,加入列表
ret.append(list(nums))
return
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start] # 交换位置
premutation(nums, start + 1, ret) # 深入
nums[start], nums[i] = nums[i], nums[start] # 恢复状态
ret = []
permutations(nums, 0, ret)
print(ret)
nums = [1,2,3]
permute(nums)
#输出结果:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
- 如果不是特别明白的单步跟踪一下。