题目
给你一个整数数组 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] <= 10
nums 中的所有元素 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
二进制解法求子集
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length==0) return res;
int n=nums.length;
for(int i=0;i<(1<<n);i++){
List<Integer> tmp = new ArrayList<>();
for(int j=0;j<n;j++){
if((i&(1<<j))>0){
tmp.add(nums[j]);
}
}
res.add(tmp);
}
return res;
}
}
回溯算法求解子集
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
if(nums.length==0) return res;
backtracing(0,nums);
return res;
}
public void backtracing(int idx,int[] nums){
if(idx==nums.length){
res.add(new ArrayList<>(tmp));
return;
}
tmp.add(nums[idx]); //选择当前元素
backtracing(idx+1,nums);
tmp.remove(tmp.size()-1); //不选择当前元素
backtracing(idx+1,nums);
}
}
总结
移除当前List最后一个元素
list.remove(list.size()-1)