Go语言实现全排列(LeetCode 46)

Go语言实现全排列(LeetCode 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
}
posted @ 2021-05-26 10:51  小尾学长  阅读(599)  评论(0编辑  收藏  举报