78. 子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的
子集
(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
这题在评论区看到好的解法了
https://leetcode.cn/problems/subsets/solutions/420294/zi-ji-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked
这个评论
yukiyama
发布于 江苏(编辑过)
2022.03.30
思路及代码
例如[1,2,3],一开始解集为[[]],表示只有一个空集。
遍历到1时,依次拷贝解集中所有子集,只有[],把1加入拷贝的子集中得到[1],然后加回解集中。此时解集为[[], [1]]。
遍历到2时,依次拷贝解集中所有子集,有[], [1],把2加入拷贝的子集得到[2], [1, 2],然后加回解集中。此时解集为[[], [1], [2], [1, 2]]。
遍历到3时,依次拷贝解集中所有子集,有[], [1], [2], [1, 2],把3加入拷贝的子集得到[3], [1, 3], [2, 3], [1, 2, 3],然后加回解集中。此时解集为[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]。
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> lists = new ArrayList<>(); // 解集
lists.add(new ArrayList<Integer>()); // 首先将空集加入解集中
for(int i = 0; i < nums.length; i++){
int size = lists.size(); // 当前子集数
for(int j = 0; j < size; j++){
List<Integer> newList = new ArrayList<>(lists.get(j));// 拷贝所有子集
newList.add(nums[i]); // 向拷贝的子集中加入当前数形成新的子集
lists.add(newList); // 向lists中加入新子集
}
}
return lists;
}
}