How to find all possible subsets of a given array?

后端 未结 4 882
南笙
南笙 2020-11-28 13:57

I want to extract all possible sub-sets of an array in C# or C++ and then calculate the sum of all the sub-set arrays\' respective elements to check how many of them are equ

4条回答
  •  执念已碎
    2020-11-28 14:39

    It's been one of my college projects 4/5 years ago, and I can't remind the algorithm well. As I see & my memory serves it's using an array as the original set and a bitmask to indicate what elements are present in the current subset.
    here's the un-tested code from the archive:

    #include 
    
    #ifndef H_SUBSET
    #define H_SUBSET
    
    template 
    class Subset {
        private:
            int Dimension;
            T *Set;
            bool *Bitmask;
        public:
            Subset(T *set, int dim);
            ~Subset(void);
            void Show(void);
            void NextSubset(void);
            void EmptySet(void);
            void FullSet(void);
            int SubsetCardinality(void);
            int SetCardinality(void);
            T operator[](int index);
    };      
    
    template 
    int Subset::SetCardinality(void) {
        return Dimension;
    }
    
    template 
    int Subset::SubsetCardinality(void) {
        int dim = 0;
        for(int i = 0; i
    void Subset::EmptySet(void) {
        for(int i = 0; i
    void Subset::FullSet(void) {
        for(int i = 0; i
    void Subset::NextSubset(void) {
        int i = Dimension - 1;
        while(!Bitmask[i]&&i>=0) {
            i--;
            if(i<0) {
                break;
            }
        }
        if(i>=0) {
            Bitmask[i] = !Bitmask[i];
        }
        for(int j = i+1; j < Dimension; j++) {
            Bitmask[j] = !Bitmask[j];
        }
        return;
    }
    
    template 
    void Subset::Show(void) {
        std::cout << "{ ";
        for(int i=0; i
    Subset::Subset(T *set, int dim) {
        Set = new T[dim];
        Bitmask = new bool[dim];
        Dimension = dim;
        for(int i=0; i
    Subset::~Subset(void) {
        delete [] Set;
        delete [] Bitmask;
    }
    #endif // H_SUBSET
    

    And if it's your homework, you're killing yourself bro ;)

提交回复
热议问题