- 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
funcsubsets(nums []int) [][]int {
rets:= [][]int{}
iflen(nums) ==0 {
returnrets
}
currentIndex:=make([]int, len(nums))
fori:=rangecurrentIndex {
currentIndex[i] =-1
}
solution:= []int{}
depth, maxDepth:=-1, len(nums)-1
for {
finish:=false
L:
fordepth<maxDepth {
for {
childDepth:=depth+1
preIndex:=currentIndex[childDepth]
ifpreIndex==len(nums)-1 {
finish=true
currentIndex[childDepth] =-1
break L
}
currentIndex[childDepth]++
ifdepth==-1||nums[currentIndex[depth]] <nums[currentIndex[childDepth]] {
solution=append(solution, nums[currentIndex[childDepth]])
break
}
}
depth++
}
iffinish||depth==maxDepth {
cp:=make([]int, len(solution))
copy(cp, solution)
rets=append(rets, cp)
finish=false
}
ifdepth==-1 {
break
}
depth--
solution=solution[:len(solution)-1]
}
returnrets
}