Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Created October 13, 2018 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibreathebsb/1055a867d1e7d54b6606bbb753d9fffb to your computer and use it in GitHub Desktop.
Save ibreathebsb/1055a867d1e7d54b6606bbb753d9fffb to your computer and use it in GitHub Desktop.
LeetCode 40. Combination Sum II
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
var result [][]int
var dfs func([]int, int, []int, int)
dfs = func(candidates []int, startIndex int, currentSet []int, newTarget int) {
if newTarget == 0 {
newSet := make([]int, len(currentSet))
copy(newSet, currentSet)
result = append(result, newSet)
return
}
if newTarget < 0 {
return
}
for i := startIndex; i < len(candidates); i++ {
if i > startIndex && candidates[i] == candidates[i-1] {
continue
}
currentSet = append(currentSet, candidates[i])
dfs(candidates, i+1, currentSet, newTarget-candidates[i])
currentSet = currentSet[:len(currentSet)-1]
}
}
dfs(candidates, 0, make([]int, 0), target)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment