-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathsubsets.go
47 lines (46 loc) · 959 Bytes
/
subsets.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
package subsets
func subsets(nums []int) [][]int {
rets := [][]int{}
if len(nums) == 0 {
return rets
}
currentIndex := make([]int, len(nums))
for i := range currentIndex {
currentIndex[i] = -1
}
solution := []int{}
depth, maxDepth := -1, len(nums)-1
for {
finish := false
L:
for depth < maxDepth {
for {
childDepth := depth + 1
preIndex := currentIndex[childDepth]
if preIndex == len(nums)-1 {
finish = true
currentIndex[childDepth] = -1
break L
}
currentIndex[childDepth]++
if depth == -1 || nums[currentIndex[depth]] < nums[currentIndex[childDepth]] {
solution = append(solution, nums[currentIndex[childDepth]])
break
}
}
depth++
}
if finish || depth == maxDepth {
cp := make([]int, len(solution))
copy(cp, solution)
rets = append(rets, cp)
finish = false
}
if depth == -1 {
break
}
depth--
solution = solution[:len(solution)-1]
}
return rets
}