From 03028b1a41567b2a9bfa1f4c4f8d4d5e6cc4264c Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Sat, 29 Jul 2023 17:13:12 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=20slice.Combinations?= =?UTF-8?q?=20=E6=95=88=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/slice/slice.go | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/utils/slice/slice.go b/utils/slice/slice.go index 756f458..70d6e12 100644 --- a/utils/slice/slice.go +++ b/utils/slice/slice.go @@ -1,7 +1,6 @@ package slice import ( - "fmt" "math/rand" "reflect" ) @@ -221,27 +220,13 @@ func GetIndexAny[V any](slice []V, values V) int { // Combinations 获取给定数组的所有组合,包括重复元素的组合 func Combinations[T any](a []T) [][]T { - n := len(a) - - // 去除重复元素,保留唯一元素 - uniqueSet := make(map[string]bool) - uniqueSlice := make([]T, 0, n) - for _, val := range a { - ptr := fmt.Sprintf("%p", val) - if !uniqueSet[ptr] { - uniqueSet[ptr] = true - uniqueSlice = append(uniqueSlice, val) - } - } - - n = len(uniqueSlice) // 去重后的数组长度 - totalCombinations := 1 << n // 2的n次方 var result [][]T - for i := 0; i < totalCombinations; i++ { + n := len(a) + for i := 0; i < (1 << n); i++ { var currentCombination []T for j := 0; j < n; j++ { if (i & (1 << j)) != 0 { - currentCombination = append(currentCombination, uniqueSlice[j]) + currentCombination = append(currentCombination, a[j]) } } result = append(result, currentCombination)