forked from hoanhan101/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subsets_test.go
64 lines (52 loc) · 1.22 KB
/
subsets_test.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
/*
Problem:
- Given a set with distinct elements, find all the distinct subsets.
Example:
- Input: [1 2]
Output: [[] [1] [2] [1 2]]
- Input: [1 2 5]
Output: [[] [1] [2] [1 2] [3] [1 3] [2 3] [1 2 3]]
Approach:
- Start with an empty set.
- Iterate through the set one by one and add them to existing sets to create new ones.
Cost:
- O(2^n) time, O(2^n) space since we would have a total of 2^n subsets.
*/
package gtci
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestFindSubsets(t *testing.T) {
tests := []struct {
in []int
expected [][]int
}{
{[]int{}, [][]int{{}}},
{[]int{1}, [][]int{{}, {1}}},
{[]int{1, 2}, [][]int{{}, {1}, {2}, {1, 2}}},
{[]int{1, 2, 3}, [][]int{{}, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}}},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
findSubsets(tt.in),
)
}
}
func findSubsets(nums []int) [][]int {
subsets := [][]int{}
// start with an empty set.
subsets = append(subsets, []int{})
// for each number in the set, add it to all existing sets.
for _, num := range nums {
n := len(subsets)
for i := 0; i < n; i++ {
set := subsets[i]
set = append(set, num)
subsets = append(subsets, set)
}
}
return subsets
}