1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// @Title: 全排列 (Permutations)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 4 ms
// @Memory: 7 MB
/*
 * @lc app=leetcode.cn id=46 lang=golang
 *
 * [46] 全排列
 *
 * https://leetcode-cn.com/problems/permutations/description/
 *
 * algorithms
 * Medium (71.53%)
 * Likes:    372
 * Dislikes: 0
 * Total Accepted:    45K
 * Total Submissions: 62.8K
 * Testcase Example:  '[1,2,3]'
 *
 * 给定一个没有重复数字的序列,返回其所有可能的全排列。
 *
 * 示例:
 *
 * 输入: [1,2,3]
 * 输出:
 * [
 * ⁠ [1,2,3],
 * ⁠ [1,3,2],
 * ⁠ [2,1,3],
 * ⁠ [2,3,1],
 * ⁠ [3,1,2],
 * ⁠ [3,2,1]
 * ]
 *
 */

// 回溯 + 递归
func permute(nums []int) [][]int {
	res := make([][]int, 0)
	var perm func(int)

	perm = func(k int) {
		if k == len(nums)-1 {
			tmp := make([]int, len(nums))
			copy(tmp, nums)
			res = append(res, tmp)
			return
		}

		for i := k; i < len(nums); i++ {

			// 回溯的模块, 归去来兮
			nums[i], nums[k] = nums[k], nums[i]
			perm(k + 1)
			nums[i], nums[k] = nums[k], nums[i]
		}

	}

	perm(0)
	return res
}