题目
解题思路
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
思路 [1,2,3]
对于长度为1的数组 其所有子集为 [] [1]
对于长度为2的数组 其所有子集为[] [2] [1] [1,2]
对于长度为3的数组 其所有子集为[][3] [2] [2,3] [1] [1,3] [1,2] [1,2,3]
从以上规律可以总结出来
对于长度为1的数组 其所有子集为 [] [num[0]]
对于长度为2的数组 其所有子集为 长度为1的所有子集 + 长度为1的所有子集每个子集都添上[num[1]]
对于长度为3的数组 其所有子集为 长度为2的所有子集 + 长度为2的所有子集每个子集都添上[num[2]]
Code
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
//对于第一个数字 我们添加一个空集合
res.add(new ArrayList<Integer>());
//添加第一个位置的数字
ArrayList<Integer> subOne = new ArrayList<>();
subOne.add(nums[i]);
res.add(subOne);
}else {
int newNum = nums[i];
int currLength = res.size();
for (int j = 0; j < currLength; j++) {
ArrayList<Integer> newSubSet = new ArrayList<>(res.get(j));
newSubSet.add(newNum);
res.add(newSubSet);
}
}
}
return res;
}
}
运行结果截图