leetcode 78. 子集-java实现

题目所属分类

dfs也可以二进制的求法
(i>>j&1) == 1 i的第j位是否等于1
1<<n 可以当作2 ^ n

原题链接

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

代码案例:输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

题解

普通的dfs 时间复杂度为2^n * n 如果不记方案就是2 ^ n

class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    List<Integer> path = new ArrayList<Integer>();
    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums,0,nums.length);
        return ans;
    }
    public void dfs(int[] nums,int u ,int n  ){
        if(u == n){
            ans.add(new ArrayList<>(path));
            return;
        }
        path.add(nums[u]);
        dfs(nums,u+1,n);
        path.remove(path.size()-1);
        dfs(nums,u+1,n);
    }
}

二进制的 不要忘记path.clear() 时间复杂度为2^n * n

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        int n =  nums.length ;
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> path = new ArrayList<Integer>();
        for(int i = 0 ; i < 1<<n ; i++){//枚举每个数
            path.clear();
            for(int j = 0 ; j < n ; j++){//枚举每个数的二进制数
                if((i>>j&1) == 1) path.add(nums[j]);
            }
            ans.add(new ArrayList<>(path));
        }
        return ans ;
    }
}
posted @   依嘫  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示