Leetcode 78 子集

题目定义:

给你一个整数数组 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 中的所有元素 互不相同

方式一思路解析:

​ 子集和原始数组的关系是 子集 = 2^(原始数组长度) ,假如原始数组只有一个,那么子集只有:空集和它自身;假如原始数组{1,2}有两个,那么子集就会有四个:{},{1},{2},{1,2};依次类推

​ 按照这样的关系,我们可以用一个数字的二进制表示,1表示在子集中,0表示不在子集中,例如 原始数组为:{5,2,9}时,对应的关系为:

0/1 序列 子集 0/10/1 序列对应的二进制数
000000 { }{} 00
001001 { 9 }{9} 11
010010 { 2 }{2} 22
011011 { 2, 9 }{2,9} 33
100100 { 5 }{5} 44
101101 { 5, 9 }{5,9} 55
110110 { 5, 2 }{5,2} 66
111111 { 5, 2, 9 }{5,2,9} 77

方式一(二级制位运算):

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans =new ArrayList<>();
        int n =nums.length;
        //外层循环统计所有出现的个数 范围:0-2^n
        for(int i = 0; i < (1 << n); i++){
            List<Integer> temp =new ArrayList<>();
            //依次比较每个 1 的位置取值 
            //依次:0000 0001 0011 0100 0111 等等 
            for(int j = 0; j < n; j++){
                if((i &(1 << j)) != 0)
                    temp.add(nums[j]);
            }
            ans.add(temp);
        }
        return ans;
    }
}

方式二(回溯法):

class Solution {
    private List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums,new ArrayList<>(),0);
        return ans;
    }
    private void dfs(int[] nums,List<Integer> temp,int index){
        if(index == nums.length){
            ans.add(new ArrayList<>(temp));
        }else{
            //去当前位置的值
            temp.add(nums[index]);
            dfs(nums,temp,index + 1);
            //不取当前位置的值
            temp.remove(temp.size() - 1);
            dfs(nums,temp,index + 1);
        }
    }
}
原文地址:https://www.cnblogs.com/CodingXu-jie/p/14454307.html