/**
找到该数组的所有子集(不考虑顺序)
大致执行流程(for循环 + 递归)
递归:
首先以index为起点,将上一层的temp添加到res中(第一次temp为空),以index为起点,访问当前元素,添加到res中
首先以index + 1为起点,将上一层的temp添加到res中,以index + 1为起点,访问当前元素,添加到res中
直到访问完所有元素,此时res中[1],[1,2],[1,2,3]。
回溯:
回退tempResult的状态,index回到上一层,迭代i访问可访问的下一个元素添加到tempResult中,直到i到尽头当前层结束
再次回退tempResult与index,重复上述流程迭代i,直到访问完所有结果
细节:
index除了控制可访问的元素外,还隐含了每层结果中元素个数
*/
class Solution {
//保存所有结果
private List<List<Integer>> res = new ArrayList<>();
//临时保存单次结果
private List<Integer> tempResult = new ArrayList<>();
//避免重复传参
private int[] nums;
public List<List<Integer>> subsets(int[] nums) {
/**
找到该数组的所有子集(不考虑顺序)
大致执行流程(for循环 + 递归)
递归:
首先以index为起点,将上一层的temp添加到res中(第一次temp为空),以index为起点,访问当前元素,添加到res中
首先以index + 1为起点,将上一层的temp添加到res中,以index + 1为起点,访问当前元素,添加到res中
直到访问完所有元素,此时res中[1],[1,2],[1,2,3]。
回溯:
回退tempResult的状态,index回到上一层,迭代i访问可访问的下一个元素添加到tempResult中,直到i到尽头当前层结束
再次回退tempResult与index,重复上述流程迭代i,直到访问完所有结果
细节:
index除了控制可访问的元素外,还隐含了每层结果中元素个数
*/
this.nums = nums;
backtrack(0);
return res;
}
private void backtrack(int index) {
res.add(List.copyOf(tempResult)); //深拷贝
//代表所有元素都被访问过
if(index == nums.length) {
return;
}
for(int i = index; i < nums.length; i++) {
//保存当前元素
tempResult.add(nums[i]);
backtrack(i + 1); //递归调用,从i + 1开始
//回溯 回退tempRes的状态
tempResult.remove(tempResult.size() - 1);
}
}
}