题目:
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
- nums 中的所有元素 互不相同
解法1:递归
/**
* 思路:
* 获取每个数,每次递归都是当前数+1,找到其所有的组合,每次都加入结果集
* 递归结束后删除这个数
* []
* 1的所有可能:1,12,123,12,13,1
* 2的所有可能:2,23,2
* 3的所有可能:3
*/
public List<List<Integer>> subsets(int[] nums) {
ArrayList<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> queue = new LinkedList<>();
result.add(new ArrayList<>());
recursive(result,queue,nums,0);
return result;
}
private void recursive(ArrayList<List<Integer>> result, LinkedList<Integer> queue, int[] nums, int lattice) {
for (int i=lattice;i<nums.length;i++){
queue.offer(nums[i]);
result.add(new ArrayList<>(queue));
recursive(result, queue, nums, i+1);
queue.removeLast();
}
}
时间复杂度:On
空间复杂度:On
解法2:递归(放格子)
public List<List<Integer>> subsets(int[] nums) {
ArrayList<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> queue = new LinkedList<>();
recursive(result,queue,nums,0);
return result;
}
private void recursive(ArrayList<List<Integer>> result, LinkedList<Integer> queue, int[] nums, int lattice) {
if (lattice==nums.length){
result.add(new ArrayList<>(queue));
return;
}
recursive(result, queue, nums, lattice+1);
queue.offer(nums[lattice]);
recursive(result, queue, nums, lattice+1);
queue.removeLast();
}
时间复杂度:On
空间复杂度:On
解法3:迭代
/**
* 思路:
* 每增加一个元素让之前所有的结果集中加入这个元素
*/
public List<List<Integer>> subsets(int[] nums) {
ArrayList<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (int num:nums){
int size = result.size();
for (int i=0;i<size;i++){
List<Integer> list = new ArrayList<>(result.get(i));
list.add(num);
result.add(list);
}
}
return result;
}
时间复杂度:On^2
空间复杂度:On
解法4:位运算
/**
* 思路:
* 每个数有两个选择,放入格子,或者不放入。
* 因此结果集的长度是2^n
* 比如数组1,2,3
* 有8种可能性,用0表示不放,1表示放。正好可以用1-8的二进制数表示放或不放
* (res_index >> index) & 1查看当前位是否放元素
*
*/
public List<List<Integer>> subsets(int[] nums) {
ArrayList<List<Integer>> result = new ArrayList<>();
for (int result_index = 0; result_index < 1 << nums.length; result_index++) {
ArrayList<Integer> list = new ArrayList<>();
for (int index = 0; index < nums.length; index++) {
if (((result_index >> index) & 1) == 1) list.add(nums[index]);
}
result.add(list);
}
return result;
}
时间复杂度:On^2
空间复杂度:On