From 370c61deb66493ea588623fb7657128e92945ec0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 21 May 2024 11:38:23 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB78.=20Subsets=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/subsets.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 go/subsets.go diff --git a/go/subsets.go b/go/subsets.go new file mode 100644 index 0000000..52fc3f8 --- /dev/null +++ b/go/subsets.go @@ -0,0 +1,29 @@ +package subsets + +func subsets(nums []int) [][]int { + var sets [][]int + + var subsetsRec func(int) + + var runningSet []int + subsetsRec = func(i int) { + if i == len(nums) { + toAppend := make([]int, len(runningSet)) + copy(toAppend, runningSet) + + sets = append(sets, toAppend) + return + } + + // Skip the current element + subsetsRec(i + 1) + + // Include the current element + runningSet = append(runningSet, nums[i]) + subsetsRec(i + 1) + runningSet = runningSet[:len(runningSet)-1] + } + + subsetsRec(0) + return sets +}