【回溯】78. 子集

题目:

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
[3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

 

解答:

方法一:迭代法

 

 

 

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        for(int m = 0;m<(1<<n);m++){
            List<Integer> tmp = new ArrayList<>();
            for(int i = 0;i<n;i++){
                if((m & (1<<i)) !=0){
                    tmp.add(nums[i]);
                }
            }
            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) {
        dfs(0,nums);
        return res;
    }
    public void dfs(int cur,int[] nums){
        if(cur == nums.length){
            res.add(new ArrayList<Integer>(tmp));
            return;
        }
        tmp.add(nums[cur]);
        dfs(cur+1,nums);
        tmp.remove(tmp.size()-1);
        dfs(cur+1,nums);
    }
}

 

posted @ 2020-10-09 20:35  3KBLACK  阅读(66)  评论(0)    收藏  举报