思路:
子集很好理解,当然也要包括空和本身。其他的就是当前数组的一部分元素了。如何解决呢?
对于当前值来说,我可以不要,也可以要,两种方式,下一个也是,一直到index==length为止,收集完一种排列。还有最重要,收集用的list一定要还原。代码如下:
class Solution {
public static List<List<Integer>> subsets(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> list = new ArrayList<>();
List<Integer> childList = new ArrayList<>();
process(nums, 0, nums.length, list, childList);
return list;
}
private static void process(int[] nums, int index, int N, List<List<Integer>> list, List<Integer> childList) {
if (index == N) {
list.add(new ArrayList<>(childList));
} else {
// 不要当前值
process(nums, index + 1, N, list, childList);
// 要当前值
childList.add(nums[index]);
process(nums, index + 1, N, list, childList);
// 重点 移除加入的数,重新分类
childList.remove(childList.size() - 1);
}
}
}