-
Notifications
You must be signed in to change notification settings - Fork 0
/
39.go
49 lines (39 loc) · 1010 Bytes
/
39.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
func main() {
combinationSum([]int{2, 3, 1}, 9)
}
func combinationSum(candidates []int, target int) [][]int {
result := [][]int{}
for i, x := range candidates {
if x > target {
continue
} else if x == target {
result = append(result, []int{x})
continue
}
a := backTracking(candidates, target, i, []int{candidates[i]})
result = append(result, a...)
}
return result
}
func backTracking(candidates []int, target int, index int, sn []int) [][]int {
result := [][]int{}
// wrong answer if remove this. don't know why
startNums := make([]int, len(sn))
copy(startNums, sn)
s := 0
for _, x := range startNums {
s += x
}
for i := index; i < len(candidates); i++ {
if (s + candidates[i]) > target {
continue
} else if (s + candidates[i]) == target {
result = append(result, append(startNums, candidates[i]))
continue
}
a := backTracking(candidates, target, i, append(startNums, candidates[i]))
result = append(result, a...)
}
return result
}