-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00039-combination_sum.go
More file actions
44 lines (32 loc) · 927 Bytes
/
00039-combination_sum.go
File metadata and controls
44 lines (32 loc) · 927 Bytes
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
// 39: Combination Sum
// https://leetcode.com/problems/combination-sum/
package main
import "fmt"
func backtrack(candidates []int, target int, start int, current []int, result *[][]int) {
if start >= len(candidates) || target < 0 {return}
if target == 0 {
t := make([]int, len(current))
copy(t, current)
*result = append(*result, t)
return
}
current = append(current, candidates[start])
backtrack(candidates, target - candidates[start], start, current, result)
current = current[:len(current)-1]
backtrack(candidates, target, start + 1, current, result)
}
// SOLUTION
func combinationSum(candidates []int, target int) [][]int {
var current []int
var result [][]int
backtrack(candidates, target, 0, current, &result)
return result
}
func main() {
// INPUT
candidates := []int{2,3,6,7}
target := 7
// OUTPUT
result := combinationSum(candidates, target)
fmt.Println(result)
}