ホームページ  >  記事  >  Java  >  パワーセット

パワーセット

DDD
DDDオリジナル
2024-09-19 06:19:33346ブラウズ

Power set

問題

後戻りアプローチ:
TC:(2^n) つまり、指数関数的な時間計算量 (再帰呼び出しごとに 2 つの選択肢が残されているため、つまり 'index' の値を考慮するか、2 つの可能な結果を​​もたらす考慮しないかのどちらかであるため、これは n 回発生します)
SC:(2^n)*(n)、一時 ArrayList<>() の場合は n、メイン ArrayList<>() の場合は 2^n;

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。