LeetCode-46.全排列

题目描述

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例

1
2
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
1
2
输入:nums = [0,1]
输出:[[0,1],[1,0]]

提示

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同

题解

辅助状态变量:

  • depth:递归到第几层
  • path:已经选了哪些数
  • used:布尔数组,表示某个位置的数是否被用过
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func permute(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
var used = Array(repeating: false, count: nums.count)

func backTrace(_ depth: Int) {
if depth == nums.count {
res.append(path)
return
}
for i in 0 ..< nums.count {
if !used[i] {
path.append(nums[i])
used[i] = true
backTrace(depth + 1)
path.removeLast()
used[i] = false
}
}
}
backTrace(0)
return res
}