-
Notifications
You must be signed in to change notification settings - Fork 0
/
子集.go
43 lines (40 loc) · 921 Bytes
/
子集.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
package pos
import "fmt"
// 解法1
func subsets(nums []int) [][]int {
result := make([][]int, 0)
item := make([]int, 0)
result = append(result, item)
generate(0, nums, &item, &result)
return result
}
func generate(i int, nums []int, item *[]int, result *[][]int) {
if i >= len(nums) {
return
}
*item = append(*item, nums[i])
*result = append(*result, *item)
generate(i+1, nums, item, result)
// itemArr := *item
// *item = append([]int{}, itemArr[:len(*item)-1]...)
*item = (*item)[:len(*item)-1]
generate(i+1, nums, item, result)
}
// 解法2
func subsets2(nums []int) [][]int {
n := len(nums)
all_set := 1 << n
result := make([][]int, 0)
// item := make()
for i := 0; i < all_set; i++ {
item := make([]int, 0)
for j := 0; j < n; j++ {
if i&(1<<j) > 0 {
item = append(item, nums[j])
fmt.Println(j, item, nums, nums[j])
}
}
result = append(result, item)
}
return result
}