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],
[]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
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)
//add number into []int
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
for mask := 0; mask < 1<<n; mask++ {
set := []int{}
//add num into the result follow the mask
for i, v := range nums {
if mask>>i&1 > 0 {
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: