46. Permutations Given a collection of distinct integers, return all possible permutations.
Example:
代码语言:javascript复制Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:
题目意思很简单就是求出一个数组的排列组合,思路就是使用回溯来做。
代码:
go:
代码语言:javascript复制func permute(nums []int) [][]int {
var res [][]int
dfs(0, nums, &res)
return res
}
func dfs(start int, nums []int, res *[][]int){
if start == len(nums) {
*res = append(*res, append([]int{}, nums...))
return
}
for i := start; i < len(nums); i {
nums[i], nums[start] = nums[start], nums[i]
dfs(start 1, nums, res)
nums[start], nums[i] = nums[i], nums[start]
}
}