题目描述
Description
Given a set of distinct integers, return all possible subsets.
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
Example
If S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Challenge
Can you do it in both recursively and iteratively?
大致是给一个无序数组,让你求它的子集
递归解法
先说说递归吧,比较简单
递归出口
if (nums.length == n) {
result.add(new ArrayList<>(ints));
return;
}
将数组集合中的每个元素依次加进去,再拿出来继续进行递归
ints.add(nums[n]);
helper(nums, ints, result, n + 1);
ints.remove(ints.size() - 1);
helper(nums, ints, result, n + 1);
全部代码如下
public List<List<Integer>> subsets(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
helper(nums, new ArrayList<>(), result, 0);
return result;
}
private void helper(int[] nums,
ArrayList<Integer> ints,
List<List<Integer>> result,
int n) {
//递归出口
if (nums.length == n) {
result.add(new ArrayList<>(ints));
return;
}
ints.add(nums[n]);
helper(nums, ints, result, n + 1);
ints.remove(ints.size() - 1);
helper(nums, ints, result, n + 1);
}
非递归解法
非递归解法是这样的,用二进制01代表该数组元素有没有被选中,然后判断该元素需不需要添加进去
举例,nums[1,2]
结果如下:
i | bin | n |
---|---|---|
0 | 00 | [] |
1 | 01 | [1] |
2 | 10 | [2] |
3 | 11 | [1,2] |
代码如下
public List<List<Integer>> subsets(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < (1 << nums.length); i++) {
List<Integer> n = new ArrayList<>();
for (int j = 0; j < nums.length; j++) {
if ((i & (1 << j)) != 0) {
n.add(nums[j]);
}
}
}
return result;
}