46. 全排列)
简单粗暴回溯法
func permute(nums []int) [][]int {
res := [][]int{}
visited := map[int]bool{}
var dfs func(path []int)
dfs = func(path []int) {
if len(path) == len(nums) {
temp := make([]int, len(path))
copy(temp, path)
res = append(res, temp)
return
}
for _, n := range nums {
if visited[n] {
continue
}
path = append(path, n)
visited[n] = true
dfs(path)
path = path[:len(path)-1]
visited[n] = false
}
}
dfs([]int{})
return res
}
|
请发表评论