全排列
题目描述:
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解题思路:
利用标记数组和递归来解决问题
- 我们核心思想是创建一个标记数组
mark
来表示每一位数字在进行全排列的时候的使用情况,使用的数字在相同下标位置标记为True
,反之为False
- 然后通过循环,将不同数字作为起始位;通过遍历,将其后的数字填入依序填入;通过标记数组来保证数字使用的唯一性
Python源码:
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
mark = [False] * len(nums) # 标记数字使用的数组
outcome = [] # 结果数组
curr = [] # 保存一次结果数组
self.permutation_solve(mark, nums, curr, outcome)
return outcome
def permutation_solve(self, mark, nums, curr, outcome):
if sum(mark) == len(nums): # 如果三个数字都被使用过
outcome.append(curr[:])
for i in range(len(nums)):
if mark[i]: # 如果某一个数字被使用了,就跳过
continue
curr.append(nums[i])
mark[i] = True
self.permutation_solve(mark, nums, curr, outcome)
mark[i] = False
curr.pop()
欢迎关注我的github:https://github.com/UESTCYangHR