leetcode刷题笔记(Golang)--46. Permutations

46. Permutations

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]
]
这里有个需要染色的动作应该注意一下

func permute(nums []int) [][]int {
	res := &[][]int{}
	var colors []int
	for i := 0; i < len(nums); i++ {
		colors = append(colors, 0)
	}
	dfs(nums, 0, []int{}, &colors, res)
	return *res
}

func dfs(graph []int, index int, path []int, colors *[]int, ans *[][]int) {
	if len(path) == len(graph) {
		*ans = append(*ans, path)
		return
	}

	for i, v := range graph {
		if (*colors)[i] == 1 {
			continue
		}
		(*colors)[i] = 1
		dfs(graph, index+1, append(path, v), colors, ans)
		(*colors)[i] = 0
	}
}
发布了65 篇原创文章 · 获赞 0 · 访问量 391

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104257473