题目
描述
给出一组数字,返回该组数字的所有排列
例如:
[1,2,3]的所有排列如下
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], [3,2,1].
(以数字在数组中的位置靠前为优先级,按字典序排列输出。)
数据范围:数字个数 0<n≤6
要求:空间复杂度 O(n!) ,时间复杂度 O(n!)
思路
全排列的问题直接使用深度优先遍历
代码
python版本:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param num int整型一维数组
# @return int整型二维数组
#
class Solution:
def permute(self , num: List[int]) -> List[List[int]]:
# write code here
curr = []
store = num
res = []
def dfs(curr, store):
nonlocal res
if len(store)==0:
res.append(curr)
for i in range(len(store)):
dfs(curr+[store[i]], store[:i]+store[i+1:])
dfs(curr, store)
return res
c++版本:
无