MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / combinationSum2

Function combinationSum2

go/0040-combination-sum-ii.go:5–30  ·  view source on GitHub ↗
(candidates []int, target int)

Source from the content-addressed store, hash-verified

3import "sort"
4
5func combinationSum2(candidates []int, target int) [][]int {
6 ans := make([][]int, 0)
7 curr := make([]int, 0)
8 sort.Ints(candidates)
9 var backtrack func(idx int, currSum int, curr []int)
10 backtrack = func(idx int, currSum int, curr []int) {
11 if currSum == target {
12 ans = append(ans, append([]int{}, curr...))
13 return
14 }
15 if currSum > target {
16 return
17 }
18 for i := idx; i < len(candidates); i++ {
19 if i > idx && candidates[i] == candidates[i-1] {
20 continue
21 }
22 curr = append(curr, candidates[i])
23 backtrack(i+1, currSum+candidates[i], curr)
24 curr = curr[:len(curr)-1]
25 }
26
27 }
28 backtrack(0, 0, curr)
29 return ans
30}

Callers

nothing calls this directly

Calls 1

backtrackFunction · 0.70

Tested by

no test coverage detected