Skip to content

Commit 425a470

Browse files
committed
feat(leetcode/medium/39-combination-sum.go)
1 parent 5142beb commit 425a470

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
39-combination-sum
3+
leetcode/medium/39. Combination Sum
4+
URL: https://leetcode.com/problems/combination-sum/
5+
*/
6+
7+
package main
8+
9+
import (
10+
"fmt"
11+
"sort"
12+
)
13+
14+
func backtrack(candidates []int, target int, path []int, result *[][]int, resultSet *map[string]bool) {
15+
if target < 0 {
16+
return
17+
}
18+
19+
if target == 0 {
20+
sort.Ints(path)
21+
key := fmt.Sprintf("%v", path)
22+
23+
if _, ok := (*resultSet)[key]; !ok {
24+
*result = append(*result, path)
25+
(*resultSet)[key] = true
26+
}
27+
return
28+
}
29+
30+
for i := len(candidates) - 1; i >= 0; i-- {
31+
new_path := append([]int{candidates[i]}, path...)
32+
backtrack(candidates, target-candidates[i], new_path, result, resultSet)
33+
}
34+
}
35+
36+
func combinationSum(candidates []int, target int) [][]int {
37+
sort.Ints(candidates)
38+
39+
var result [][]int
40+
var path []int
41+
var resultSet = make(map[string]bool)
42+
43+
backtrack(candidates, target, path, &result, &resultSet)
44+
45+
return result
46+
}
47+
48+
func main() {
49+
candidates := []int{2, 3, 6, 7}
50+
target := 7
51+
//fmt.Println(combinationSum(candidates, target))
52+
//Output: [[2, 2, 3], [7]]
53+
54+
candidates = []int{2, 3, 5}
55+
target = 8
56+
//fmt.Println(combinationSum(candidates, target))
57+
//Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
58+
59+
candidates = []int{2}
60+
target = 1
61+
//fmt.Println(combinationSum(candidates, target))
62+
//Output: []
63+
64+
candidates = []int{7, 3, 2}
65+
target = 18
66+
fmt.Println(combinationSum(candidates, target))
67+
//[[7,7,2,2],[7,3,3,3,2],[7,3,2,2,2,2],[3,3,3,3,3,3],[3,3,3,3,2,2,2],[3,3,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2]]
68+
}

0 commit comments

Comments
 (0)