Find all subsets of length k in an array

前端 未结 13 1684
梦谈多话
梦谈多话 2020-11-27 05:34

Given a set {1,2,3,4,5...n} of n elements, we need to find all subsets of length k .

For example, if n = 4 and k = 2, the output would be

13条回答
  •  有刺的猬
    2020-11-27 05:52

    Here is a Java version of what I think Simple is talking about, using a binary representation of all sets in the power set. It's similar to how Abhiroop Sarkar did it, but I think a boolean array makes more sense than a string when you are just representing binary values.

    private ArrayList> getSubsets(int m, Object[] objects){
        // m = size of subset, objects = superset of objects
        ArrayList> subsets = new ArrayList<>();
        ArrayList pot = new ArrayList<>();
        int n = objects.length;
        int p = 1;
        if(m==0)
            return subsets;
        for(int i=0; i<=n; i++){
            pot.add(p);
            p*=2;
        }
        for(int i=1; i=0; j--){
                int currentPot = pot.get(j);
                if(y >= currentPot){
                    binArray[j] = true;
                    y -= currentPot;
                    sum++;
                }
                if(y<=0)
                    break;
            }
            if(sum==m){
                ArrayList subsubset = new ArrayList<>();
                for(int j=0; j < n; j++){
                    if(binArray[j]){
                        subsubset.add(objects[j]);
                    }
                }
                subsets.add(subsubset);
            }
        }
    
        return subsets;
    }
    
        

    提交回复
    热议问题