Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解题思路
- 递归(cur + remain, *result)
- 特别注意 append 的坑,不要直接 append remain 的两个子切片,这会损坏原 remain 切片
- 正确的做法是新建切片,然后向新切片 append(切记切记)
func core(cur, remain []int, result *[][]int) {
if len(remain) == 0 {
cur_t := make([]int, len(cur)) // 非常重要
copy(cur_t, cur)
*result = append(*result, cur_t)
return
}
for i, v := range remain {
cur_t := append(cur, v)
remain_t := make([]int, len(remain[:i])) // 非常重要
copy(remain_t, remain[:i])
remain_t = append(remain_t, remain[i+1:]...)
core(cur_t, remain_t, result)
}
}
func permute(nums []int) [][]int {
result := [][]int{}
core([]int{}, nums, &result)
return result
}