Given a set S, find all the maximal subsets whose sum <= k

后端 未结 6 1447
感动是毒
感动是毒 2021-02-14 21:52

This is a Facebook interview question I came across at an online portal.

Given a set S, find all the maximal subsets whose sum <= k. For example, if S = {1, 2, 3, 4,

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 21:57

    This is a powerset problem. Recently I found this website about algorithms and it's been painting my imagination: hence the powerset/combinations solution following. You can simply copy, paste, and run the program.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class Solution {
      public static void maximalSubset
        (int sum, int[] set, int choose,List exclusion) {
        if(1>choose) return;
        int combinationSize = combinationSize(set.length,choose);
        int index[]=new int[choose];
        Integer subSet[] = new Integer[choose];
        for(int i=0; in-r) {
            den=n-r;
            limit=r;
        }else {
            den=r;
            limit=n-r;
        }
        long result=1;
        for(int i=n; i>limit;i--)
            result*=i;
        for(int i=2; i<=den;i++)
            result/=i;
        return (int)result;
    }//
    private static void nextCombination(int[] A, int n) {
        int c=A.length;
        int i=c-1;
        while(n-c+i==A[i])
            i--;
        A[i]++;
        for(int j=i; j=0;
    }//
    
    private static boolean excluded(Integer[] needle,List haystack) {
    
        for(Integer[] H: haystack) {
            int count=0;
            for(int h: H)
                for(int n:needle)
                    if(h==n) {
                        count++;
                        break;//it's a set
                    }
            if(count==needle.length)
                return true;
        }
        return false;
    }//
    
    public static void main(String[] args) {
        int[] S = {1, 2, 3, 4, 5};
        int k = 7;
        List exclusion = new ArrayList();
        maximalSubset(k,S,S.length,exclusion);
    }
    }
    

提交回复
热议问题