78.子集
给你一个整数数组 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] <= 10nums中的所有元素 互不相同
递归遍历的时候,把所有节点都记录下来,就是要求的子集集合。
java
public static void main(String[] args) { // 测试用
int[] nums = {1,2,3};
List<List<Integer>> res = subsets(nums);
for (List<Integer> list : res) {
System.out.println(list);
}
}
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>());
helper(nums, 0, res, new ArrayList<>());
return res;
}
public static void helper(int[] nums, int cur, List<List<Integer>> res, List<Integer> temp){
if (cur >= nums.length){
return;
}
for (int i = cur; i < nums.length; i++) {
temp.add(nums[i]);
res.add(new ArrayList<>(temp));
helper(nums, i + 1, res, temp);
temp.remove(temp.size() - 1);
}
}
以上为记录分享用,代码较差请见谅