登录
首页 >  文章 >  java教程

电源组

来源:dev.to

时间:2024-12-01 16:42:19 158浏览 收藏

对于一个文章开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《电源组》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

电源组

问题

回溯方法:
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;
    }
}

理论要掌握,实操不能落!以上关于《电源组》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>