90.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func minInt(x, y int) int {
  7. if x < y {
  8. return x
  9. }
  10. return y
  11. }
  12. // Int2DSlice ...
  13. type Int2DSlice [][]int
  14. func (p Int2DSlice) Len() int { return len(p) }
  15. func (p Int2DSlice) Less(i, j int) bool {
  16. if len(p[i]) == 0 {
  17. return true
  18. }
  19. if len(p[j]) == 0 {
  20. return false
  21. }
  22. bound := minInt(len(p[i]), len(p[j]))
  23. fmt.Println(p[i][0], p[j][0], bound)
  24. for k := 0; k < bound; k++ {
  25. if p[i][k] < p[j][k] {
  26. return true
  27. }
  28. }
  29. return len(p[i]) == bound
  30. }
  31. func (p Int2DSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  32. func subsetsWithDupIter(nums []int, subsets [][]int, subsetsMap map[string]bool) [][]int {
  33. if len(nums) == 0 {
  34. return subsets
  35. }
  36. newSubsets := [][]int{}
  37. for _, set := range subsets {
  38. newSet := append(set, nums[0])
  39. if _, ok := subsetsMap[fmt.Sprint(newSet)]; ok {
  40. continue
  41. }
  42. subsetsMap[fmt.Sprint(newSet)] = true
  43. newSubsets = append(newSubsets, newSet)
  44. }
  45. return subsetsWithDupIter(nums[1:], append(subsets, newSubsets...), subsetsMap)
  46. }
  47. func subsetsWithDup(nums []int) [][]int {
  48. sort.Ints(nums)
  49. subsets := [][]int{[]int{}}
  50. subsetsMap := make(map[string]bool, 0)
  51. result := subsetsWithDupIter(nums, subsets, subsetsMap)
  52. sort.Sort(Int2DSlice(result))
  53. return result
  54. }
  55. func testSubsetsWithDup(nums []int) {
  56. subsets := subsetsWithDup(nums)
  57. fmt.Println("The subsets of", nums, "is", subsets)
  58. }
  59. func main() {
  60. nums := []int{1, 2, 1, 2}
  61. testSubsetsWithDup(nums)
  62. }