题目描述:
标签:位运算 数组 回溯算法
给你一个整数数组
nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
代码:
思路分析:不再是求树的叶子结点,子集是要求所有的节点
1、递归结束条件,没有数可取为空集时,即startIndex>=nums.length。每次递归前先将当前的path加入result,也就是记录所有节点处的结果
2、从左到右遍历,startIndex遍历
3、从上到下,回溯
4、回溯清除,删除path最后一个元素
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracing(nums,0);
return result;
}
public void backTracing(int[] nums,int startIndex){
result.add(new ArrayList<Integer>(path));
if(startIndex >= nums.length){
return;
}
for(int i = startIndex;i < nums.length;i++){
path.add(nums[i]);
backTracing(nums,i+1);
path.remove(path.size()-1);
}
}
}