LeetCode 47 全排列 II

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

示例 2:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

解答:

昨天的代码改改就好了,增加了排序,遇到重复的数就跳过

func permuteUnique(nums []int) [][]int {
	l := len(nums)
	res := make([][]int, 0)
	if l == 0 {
		return res
	}
	sort.Ints(nums)
	tmp := make([]int, 0)
	used := make([]bool, l)
	res = dfs(nums, l, 0, tmp, used, res)
	return res
}

func dfs(nums []int, l, depth int, tmp []int, used []bool, res [][]int) [][]int {
	if depth == l {
		a := make([]int, l)
		copy(a, tmp)
		return append(res, a)
	}
	for i := 0; i < l; i++ {
		if used[i] || i > 0 && !used[i-1] && nums[i] == nums[i-1] {
			continue
		}
		tmp = append(tmp, nums[i])
		used[i] = true
		res = dfs(nums, l, depth+1, tmp, used, res)
		tmp = tmp[:len(tmp)-1]
		used[i] = false
	}
	return res
}

官方解答:

1.搜索回溯

func permuteUnique(nums []int) (ans [][]int) {
	sort.Ints(nums)
	n := len(nums)
	var perm []int
	vis := make([]bool, n)
	var backtrack func(int)
	backtrack = func(idx int) {
		if idx == n {
			ans = append(ans, append([]int(nil), perm...))
			return
		}
		for i, v := range nums {
			if vis[i] || i > 0 && !vis[i-1] && v == nums[i-1] {
				continue
			}
			perm = append(perm, v)
			vis[i] = true
			backtrack(idx + 1)
			vis[i] = false
			perm = perm[:len(perm)-1]
		}
	}
	backtrack(0)
	return
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注