首页 > Java > java教程 > 正文

电源组

DDD
发布: 2024-09-19 06:19:33
原创
433 人浏览过

Power set

问题

回溯方法:
TC:(2^n) 即指数时间复杂度(因为我们在每次递归调用时都有两个选择,即要么考虑“index”处的值,要么不考虑导致 2 个可能结果的值,这将发生 n 次)
SC:(2^n)*(n),n 表示临时 ArrayList(),2^n 表示主 ArrayList();

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        powerSet(nums,0,list,new ArrayList<Integer>());
        return list;
    }
    public void powerSet(int [] nums, int index , List<List<Integer>> list, List<Integer> l){
        //base case
        if(index ==nums.length){
            list.add(new ArrayList<>(l));
            return;
        }
        //take
        l.add(nums[index]); //consider the value at 'index'
        powerSet(nums,index+1,list,l);
        //dont take;
        l.remove(l.size()-1);// don't consider the value at 'index'
        powerSet(nums,index+1,list,l);
    }
}
登录后复制

使用位操作:
TC:O(2^n)*n
SC:O(2^n)*n,(2^n 表示主列表,n 表示子集列表,并不是所有子集的大小都是 n,但我们仍然可以假设情况是这样)

先决条件:检查第i位是否已设置(有关更多详细信息,请参阅位操作提示和技巧页面)
直觉:
如果全都没有。子集表示为二进制值,
例如:如果 n = 3,即数组中有 3 个值。
将有 2^n = 8 个子集
8个子集也可以表示为

index 2 index 1 index 0 subset number
0 0 0 0
0 0 1 1
0 1 0 2
0 1 1 3
1 0 0 4
1 0 1 5
1 1 0 6
1 1 1 7

我们将考虑到,如果位值为 1,则应考虑 nums[] 中的索引值来形成子集。
这样我们就能够创建所有子集

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        int n = nums.length;
        int noOfSubset = 1<<n; // this is nothing but 2^n, i.e if there are n elements in the array, they will form 2^n subsets

        for(int num = 0;num<noOfSubset;num++){ /// all possible subsets numbers
            List<Integer> l = new ArrayList<>();
            for(int i =0;i<n;i++){// for the given subset number find which index value to pick 
                if((num & (1<<i))!=0) l.add(nums[i]); 
            }
            list.add(l);
        }
        return list;
    }
}
登录后复制

以上是电源组的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!