- Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathcombinations.go
42 lines (41 loc) · 796 Bytes
/
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
package combinations
funccombine(nint, kint) [][]int {
rets:= [][]int{}
ifn<=0||k<=0||n<k {
returnrets
}
currentInt:=make([]int, k)
solution:= []int{}
depth:=-1
maxDepth:=k-1
for {
L:
fordepth<maxDepth {
for {
childDepth:=depth+1
preInt:=currentInt[childDepth]
ifpreInt==n {
currentInt[childDepth] =0
break L
}
currentInt[childDepth]++
ifdepth==-1||currentInt[childDepth] >currentInt[depth] {
solution=append(solution, currentInt[childDepth])
break
}
}
depth++
}
ifdepth==maxDepth {
cp:=make([]int, len(solution))
copy(cp, solution)
rets=append(rets, cp)
}
ifdepth==-1 {
break
}
depth--
solution=solution[:len(solution)-1]
}
returnrets
}