From aa9e412aa4cfcad31fcef04ffb2b9afe499ce9ab Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 23 May 2024 20:46:11 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2597.=20The=20Number=20of=20B?= =?UTF-8?q?eautiful=20Subsets=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/the-number-of-beautiful-subsets.go | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 go/the-number-of-beautiful-subsets.go diff --git a/go/the-number-of-beautiful-subsets.go b/go/the-number-of-beautiful-subsets.go new file mode 100644 index 0000000..1ef7534 --- /dev/null +++ b/go/the-number-of-beautiful-subsets.go @@ -0,0 +1,32 @@ +package the_number_of_beautiful_subsets + +import ( + "slices" +) + +func beautifulSubsets(nums []int, k int) int { + seen := make(map[int]int) + + var dfs func(int, int) int + dfs = func(lastNum, i int) int { + // BASE: Got to the end of the slice + if i >= len(nums) { + return 1 + } + + // Initialize with skipping the current number + foundSubsets := dfs(lastNum, i+1) + + // Check if we can include the current number + if seen[nums[i]-k] == 0 && seen[nums[i]+k] == 0 { + seen[nums[i]] += 1 + foundSubsets += dfs(nums[i], i+1) + seen[nums[i]] -= 1 + } + + return foundSubsets + } + + slices.Sort(nums) + return dfs(nums[0]-k-1, 0) - 1 +}