Leecode 0046. Permutations
46. Permutations
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
1 | Input: nums = [1,2,3] |
Example 2:
1 | Input: nums = [0,1] |
Example 3:
1 | Input: nums = [1] |
题目大意
给定一个无重复元素的整数数组 nums
,返回该数组所有可能的全排列。全排列是指包含数组所有元素的有序序列,且每个元素仅出现一次,结果顺序可任意。
例如:
- 输入
nums = [1,2,3]
,输出[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
(共 3! = 6 种全排列); - 输入
nums = [0,1]
,输出[[0,1],[1,0]]
(共 2! = 2 种全排列)。
解题思路
核心思路是递归回溯 + 标记已选元素,通过逐步选择未使用的元素构建全排列,确保每个元素仅使用一次:
- 递归状态设计
- 递归函数
dfs(i)
表示:正在构建排列的第i
个位置(从 0 开始) path
数组:存储当前构建的排列,长度固定为n
(与原数组长度一致)on_path
数组:标记元素是否已被选入当前排列(on_path[j]=true
表示nums[j]
已使用)
- 递归函数
- 核心决策逻辑
- 对于排列的第
i
个位置,遍历所有未被使用的元素(on_path[j]=false
) - 选择
nums[j]
放入path[i]
,标记on_path[j]=true
- 递归处理下一个位置
i+1
- 回溯时只需将
on_path[j]
重置为false
(path
无需恢复,后续会被新值覆盖)
- 对于排列的第
- 终止条件
- 当
i == n
时,说明已构建完一个完整排列,将path
加入结果列表
- 当
- 优化点
- 使用固定长度的
path
数组,通过索引直接赋值,避免动态增减元素的开销 - 回溯时仅需恢复
on_path
状态,path
会在后续递归中被自动覆盖
- 使用固定长度的
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.