力扣:子集java
流程:
设置二维数组结果集和路径path
回溯三部曲:
参数和返回值:返回值为空,参数为输入数组和开始下标
将path输入结果集-----因为如果放在结束条件之后会无法对最后叶子节点路径加如结果集
结束条件:开始下标大于等于输入数组nums的长度
单层递归逻辑:
for循环(i=startindex;i<nums.length;i++)
节点操作:循环内将当前节点输入path
递归(nums,i+1)
回溯操作:当前节点弹出path
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();//结果集
LinkedList<Integer> path = new LinkedList<>();//当前路径
public List<List<Integer>> subsets(int[] nums) {//主函数
ziji(nums,0);//递归函数
return result;
}
public void ziji(int[] nums,int startindex){//递归函数
result.add(new ArrayList(path));//将路径输入结果集
if(startindex>nums.length) return;//结束条件:开始下标大于输入数组的长度
for(int i=startindex;i<nums.length;i++){//循环i设置为startindex,防止出现12和21为不同子集
path.offer(nums[i]);//输入当前节点进入path
ziji(nums,i+1);//递归下一层
path.removeLast();//回溯。弹出当前节点
}
}
}