Files
LeetCode-Go/website/content/ChapterFour/0047.Permutations-II.md
2020-08-09 00:39:24 +08:00

1.6 KiB
Executable File
Raw Blame History

47. Permutations II

题目

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

题目大意

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

解题思路

  • 这一题是第 46 题的加强版,第 46 题中求数组的排列,数组中元素不重复,但是这一题中,数组元素会重复,所以需要最终排列出来的结果需要去重。
  • 去重的方法是经典逻辑,将数组排序以后,判断重复元素再做逻辑判断。
  • 其他思路和第 46 题完全一致DFS 深搜即可。

代码


package leetcode

import "sort"

func permuteUnique(nums []int) [][]int {
	if len(nums) == 0 {
		return [][]int{}
	}
	used, p, res := make([]bool, len(nums)), []int{}, [][]int{}
	sort.Ints(nums) // 这里是去重的关键逻辑
	generatePermutation47(nums, 0, p, &res, &used)
	return res
}

func generatePermutation47(nums []int, index int, p []int, res *[][]int, used *[]bool) {
	if index == len(nums) {
		temp := make([]int, len(p))
		copy(temp, p)
		*res = append(*res, temp)
		return
	}
	for i := 0; i < len(nums); i++ {
		if !(*used)[i] {
			if i > 0 && nums[i] == nums[i-1] && !(*used)[i-1] { // 这里是去重的关键逻辑
				continue
			}
			(*used)[i] = true
			p = append(p, nums[i])
			generatePermutation47(nums, index+1, p, res, used)
			p = p[:len(p)-1]
			(*used)[i] = false
		}
	}
	return
}