-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombination-sum-ii.go
105 lines (95 loc) · 1.74 KB
/
combination-sum-ii.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"sort"
)
// source: https://leetcode.com/problems/combination-sum-ii/
// 1,1,2,5,6,7,10
//func deepEqual(x, y []int) bool {
// if len(x) != len(y) {
// return false
// }
// for i := range x {
// if x[i] != y[i] {
// return false
// }
// }
// return true
//}
func combinationSum2(c []int, target int) [][]int {
res := make([][]int, 0)
sort.Ints(c)
n := len(c)
var util func(arr []int, t, i int)
util = func(arr []int, t, i int) {
if t == 0 {
x := make([]int, len(arr))
copy(x, arr)
res = append(res, x)
return
}
for j := i; j < n; j++ {
if j > i && c[j] == c[j-1] {
continue
}
if c[j] > t {
break
}
arr = append(arr, c[j])
util(arr, t-c[j], j+1)
arr = arr[:len(arr)-1]
}
}
util([]int{}, target, 0)
return res
}
func main() {
testCases := []struct {
candidates []int
target int
want [][]int
}{
{
candidates: []int{3, 1, 3, 5, 1, 1},
target: 8,
want: [][]int{
{1, 1, 1, 5},
{1, 1, 3, 3},
{3, 5},
},
},
{
candidates: []int{10, 1, 2, 7, 6, 1, 5},
target: 8,
want: [][]int{
{1, 1, 6},
{1, 2, 5},
{1, 7},
{2, 6},
},
},
{
candidates: []int{2, 5, 2, 1, 2},
target: 5,
want: [][]int{
{1, 2, 2},
{5},
},
},
}
successes := 0
for _, tc := range testCases {
x := combinationSum2(tc.candidates, tc.target)
status := "ERROR"
if fmt.Sprint(x) == fmt.Sprint(tc.want) {
status = "OK"
successes++
}
fmt.Println(status, " Expected: ", tc.want, " Actual: ", x)
}
if l := len(testCases); successes == len(testCases) {
fmt.Printf("===\nSUCCESS: %d of %d tests ended successfully\n", successes, l)
} else {
fmt.Printf("===\nFAIL: %d tests failed\n", l-successes)
}
}