题目
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
class Solution {
//存储变量
List<Integer> t = new ArrayList<>();
//结果
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
//解法一: 通过是否和位移来判断
int n = nums.length; //准备n个位给他
//左移i
for(int i = 0; i < (1 << n); i ++){
t.clear(); //用之前先清零
//将结果映射到结果上
for(int j = 0; j < n; j ++){
if((i & (1 << j)) != 0){ //细心一点,这一串运算符是要加括号的
t.add(nums[j]);
}
}
//存入结果集
//result.add(t);是一个错误的写法,这里要注意这个是浅拷贝
result.add(new ArrayList<>(t));//这样子才是深拷贝
}
return result;
}
}
解法二
class Solution {
//存储变量
List<Integer> t = new ArrayList<>();
//结果
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
//方法二:递归实现
dfs(0, nums);
return result;
}
public void dfs(int cur, int[] nums){
if(cur == nums.length){
result.add(new ArrayList<>(t));
return;//结束
}
//这里不用遍历,直接往前走就是了
t.add(nums[cur]);
dfs(cur + 1, nums);
t.remove(t.size() - 1); //移出最后一个
dfs(cur + 1, nums);
}
}
```