leetcode 46. 全排列

题解

递归,首先通过交换数组头部和后序的值,然后对剩下的子数组进行递归排列

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func permute(nums []int) [][]int {
return recursion(nums, 0, len(nums)-1)
}

func recursion(nums []int, left, right int) [][]int {
res := make([][]int, 0)
if left == right {
tmp := append([]int{}, nums...)
res = append(res, tmp)
}
for i := left; i <= right; i++ {
swap(nums, i, left)
res = append(res, recursion(nums, left+1, right)...)
swap(nums, i, left)
}
return res
}

func swap(nums []int, i, j int) {
nums[i], nums[j] = nums[j], nums[i]
}