# 78. Subsets

78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Think and method：

I. Backtracking (recursion)
To see such a subset enumeration problem, backtrace should have become a natural train of thought for us, which can be divided into two cases: considering to select the current position, or not choosing the current position. For the problem backtrace(I, TMP), we need to put num[I] into TMP, perform DFS (I +1, TMP), and backtrace TMP.Keep considering the subproblem backtrace(I +1, TMP), and terminate the recursion when the value of I is equal to n to complete the answer operation.

Time complexity: O(n*2^n)
There are 2 to the n states, each of which takes order n time to construct the subset.

Space complexity: O(n)

2. Iterative method
A curious line of thought, from the official line
Let’s consider the sequence {5,2,9}
Let’s say that we have a 1 in the subset and a 0 in the subset and we don’t have a number in the subset, so we can use binary Numbers to perfectly restore the state of the subset enumeration

To be specific, it exactly corresponds to 0 to 2^n-1. Take the number in the original set according to the 0/1 sequence, for example, take {5,2}. After enumerating 2^n binary Numbers, all subsets will be constructed naturally

Time complexity: O(n*2^n)
There are 2 to the n states, each of which takes order n time to construct the subset.

Space complexity: O(n)

Code:
1、

func subsets(nums []int) [][]int {
ans := [][]int{[]int{}}

if len(nums) == 0 {
return ans
}
//function backtrace
var backtrace func(int, []int)

backtrace = func(start int, path []int) {
for i := start; i <= len(nums)-1; i++ {
tmp := make([]int, len(path))
copy(tmp, path)
tmp = append(tmp, nums[i])
//form [][]int result
ans = append(ans, append([]int{}, tmp...))
//calculate the  subproblem
backtrace(i+1, tmp)
}
}
backtrace(0, []int{})
return ans
}


2、

func subsets(nums []int) (ans [][]int) {
n := len(nums)
//enumerate mask from 0 to 2^n - 1
set := []int{}
for i, v := range nums {
set = append(set, v)
}
}
ans = append(ans, append([]int(nil), set...))
}
return ans
}


Test：
Example1:

Input: nums = [1,2,3]
Output:

Example2:

Input: nums = [1]
Output:

Example3:

Input: nums = []
Output:

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

yuSnwang

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-14
08-04 159

02-17 2176
11-08 335
04-08 1126
04-22