题目描述
// 78. 子集
// 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的
// 子集(幂集)。
// 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
题解
// 回溯搜索法
// 可以和之前的【Leetcode】39. 组合总和 和 【Leetcode】46. 全排列 放在一起看,
// 这里的backtracking回溯搜索和之前不同,以[1,2,3]为例,
// 由于需要寻找[1,2,3]的完整组合,还需要所有排列中间过程的不完整组合,
// 因此不设置显式的递归函数终止条件直接等代码块for循环结束就结束,
// backtracking传入nums,最终保存数组res,数字组合combination,循环起始位start,
// 首先将所有递归进来的combination存入res,注意要用new ArrayList(combination)
// 初始化一下,这样能把combination为[]时也考虑进去,然后for循环从start遍历到
// nums尾部,遍历元素为nums[i],将nums[i]存入combination,然后调用
// backtracking将传入的start设定为当前遍历索引i加1,即i+1,
// 递归返回之后将combination中的刚存入的尾部元素删除。
// 递归结束之后返回res。
//
// 执行用时:1 ms 在所有 Java 提交中击败了82.47%的用户
// 内存消耗:38.6 MB, 在所有 Java 提交中击败了87.08%的用户
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0)
return res;
List<Integer> combination = new ArrayList<>();
backtracking(nums, res, combination, 0);
return res;
}
public void backtracking(int[] nums, List<List<Integer>> res, List<Integer> combination, int start) {
res.add(new ArrayList(combination));
for (int i = start; i < nums.length; i++) {
combination.add(nums[i]);
backtracking(nums, res, combination, i + 1);
combination.remove(combination.size() - 1);
}
}
}