-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy patharray_sum_combinations.go
67 lines (56 loc) · 1.5 KB
/
array_sum_combinations.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
/*
WAP to take one element from each of the array add it to the target sum. Print all those three-element combinations.
A = [1, 2, 3, 3]
B = [2, 3, 3, 4]
C = [1, 2, 2, 2]
target = 7
Result:
[[1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3], [2, 3, 2], [2, 3, 2], [3, 2, 2], [3, 2, 2]]
*/
package backtrack
import (
"fmt"
"github.com/qkraudghgh/algorithms/utils"
)
type any []interface{}
var A []int = []int{1, 2, 3, 3}
var B []int = []int{2, 3, 3, 4}
var C []int = []int{1, 2, 2, 2}
func constructCandidates(constructedSofar []int) []int {
array := A
if len(constructedSofar) == 1 {
array = B
} else if len(constructedSofar) == 2 {
array = C
}
return array
}
func over(constructedSofar []int, target int) (bool, bool) {
sum := 0
toStop, reachedTarget := false, false
for _, value := range constructedSofar {
sum += value
}
if sum >= target || len(constructedSofar) >= 3 {
toStop = true
if sum == target && len(constructedSofar) == 3 {
reachedTarget = true
}
}
return toStop, reachedTarget
}
func sumCombinationsBacktrack(constructedSofar *[]int, target int) {
toStop, reachedTarget := over(*constructedSofar, target)
if toStop {
if reachedTarget {
fmt.Print(*constructedSofar)
}
return
}
candidates := constructCandidates(*constructedSofar)
for _, value := range candidates {
*constructedSofar = append(*constructedSofar, value)
sumCombinationsBacktrack(constructedSofar, target)
*constructedSofar = utils.Pop(*constructedSofar)
}
}