import (
"fmt"
"sort"
)
func subsets(nums []int) [][]int {
//存储全部集合
result := make([][]int, 0)
if len(nums) == 0 {
return result
}
//存储单次集合
path := make([]int, 0)
var backtrace func(numList []int, startIndex int)
backtrace = func(numList []int, startIndex int) {
temp := make([]int, len(path))
copy(temp, path)
result = append(result, temp)
if startIndex >= len(numList) {
return
}
for i := startIndex; i < len(numList); i++ {
path = append(path, numList[i])
backtrace(numList, i+1)
path = path[:len(path)-1]
}
}
backtrace(nums, 0)
return result
}
func subsetsWithDup(nums []int) [][]int {
//存储全部集合
result := make([][]int, 0)
if len(nums) == 0 {
return result
}
sort.Ints(nums) //排序后面做剪枝
//记录数组每一个元素是否使用过
user := make([]bool, len(nums))
//存储单次集合
path := make([]int, 0)
var backtrace func(numList []int, startIndex int)
backtrace = func(numList []int, startIndex int) {
temp := make([]int, len(path))
copy(temp, path)
result = append(result, temp)
if startIndex >= len(numList) {
return
}
for i := startIndex; i < len(numList); i++ {
if i > 0 && numList[i] == numList[i-1] && user[i-1] == false { //过滤重复
continue
}
path = append(path, numList[i])
user[i] = true
backtrace(numList, i+1)
//回溯处理
path = path[:len(path)-1]
user[i] = false
}
}
backtrace(nums, 0)
return result
}
func main() {
nums := []int{1, 2, 2}
res := subsetsWithDup(nums)
fmt.Println(res)
}