Problem
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
1 |
|
Explanation 1
-
We can use backtracking to solve this problem.
1
2
3
4
5
6
7
8
9
10
11
12+-----> "1 2" +----->"1 2 3" | +--------> " 1 "+--------+ | +-----> "1 3" | " "+---------------> " 2 "+-------> "2 3" | | | +--------> " 3 "
Solution 1
1 |
|
Explanation 2
-
When we iterate, we can either not choose the current number or choose the current number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16+------->" " +---->" "+--+ | +------->"3" +------>" "+---+ | +---->"2"+--+------->"2" " "+-+ | | +-------->"23" | | +----->"1" + +---->"1"+---+ ------>"1"+---+ +----->"13" | +---->"12"+---+----->"12" | +----->"123"
Solution 2
1 |
|
Explanation 3
- Recursive method.
1 |
|
Solution 3
1 |
|
Explanation 4
- Iterative method.
1 |
|
Solution 4
1 |
|