Power set. One way to write, all return a subset of the set. Collection does not contain duplicate elements.
Description: Solution Set can not contain duplicate subsets.
Example:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
answer:
A thought: Binary Law
First know the number of the power set of a set of n elements as: n ^ 2
the nums = [l, 2,3], of length 3, for the nums [] position, the value Fu 1, Fu does not take 0.
Such as:
a first subset 0: 0 -> [0,0,0]: []
1 subset: 1 -> [0,0,1]: [nums [0]]
2 subsets: 2-> [0,1,0]: [nums [1 ]]
of three subsets: 3 -> [0, 1 , 1]: [nums [0], nums [1]]
4 subsets: 4 -> [ 1, 0, 0]: [ nums [2]]
5 subsets: 5 -> [1, 0 , 1]: [nums [0], nums [2]]
6 subsets: 6 -> [1 , 1, 0]: [nums [1], nums [2]]
7 subset: 7 -> [1, 1 , 1]: [nums [0], nums [1], nums [2]]
JAVA code:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
// n个元素的集合,幂集个数为2^n
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
//i代表第i个集合
for (int i=0; i<(1<<n); i++){
List<Integer> temp = new ArrayList<>();
//j代表Nums[]的位置
for(int j=0; j<n; j++){
if ((i & (1<<j))!=0) {
temp.add(nums[j]);
}
}
res.add(temp);
}
return res;
}
}
Thinking two: enumeration method
= Nums [l, 2,3]
the JAVA code below
class Solution {
public List<List<Integer>> subsets1(int[] nums) {
List<List<Integer>> output = new ArrayList<>();
//初始时output中只有一个空的list
output.add(new ArrayList<>());
for (int num: nums){
List<List<Integer>> newSubsets = new ArrayList<>(); //存放每加入一个新元素后新增的子集
//产生新的子集
for (List<Integer> curr1: output) {
newSubsets.add(new ArrayList<Integer>(curr1){{add(num);}}); //这一句不是太懂
}
//将新子集加入到output中
for (List<Integer> curr2: newSubsets)
output.add(curr2);
}
return output;
}
}
Thinking three: binomial tree
May constitute a subset of all full binary, and selected from the left and right subtrees considered problem is not selected, it indicates that each layer is selected and not selected for the i-th element. So as long as you can traverse the full binary tree.
JAVA code:
public static void preOrder(List<List<Integer>> res, List<Integer> subset, int i, int[] nums){
if (i>=nums.length) return;
// 到了新的状态,记录新的路径,要重新拷贝一份
subset = new ArrayList<Integer>(subset);
res.add(subset);
preOrder(res, subset, i+1, nums);
subset.add(nums[i]);
preOrder(res, subset, i+1, nums);
}
Ideas Four: Backtracking
JAVA code:
public static void backtrack(int[] nums, int i, List<Integer> sub, List<List<Integer>> res) {
for (int j = i; j < nums.length; j++) {
sub.add(nums[j]);
res.add(new ArrayList<Integer>(sub));
backtrack(nums, j + 1, sub, res);
sub.remove(sub.size() - 1);
}
}