How to divide a set into two subsets such that difference between the sum of numbers in two sets is minimal?

前端 未结 18 734
攒了一身酷
攒了一身酷 2020-11-27 10:55

Given a set of numbers, divide the numbers into two subsets such that difference between the sum of numbers in two subsets is minimal.

T

18条回答
  •  生来不讨喜
    2020-11-27 11:50

    int ModDiff(int a, int b)
    {
        if(a < b)return b - a;
        return a-b;
    }
    
    int EqDiv(int *a, int l, int *SumI, int *SumE)
    {
        static int tc = 0;
        int min = ModDiff(*SumI,*SumE);
        for(int i = 0; i < l; i++)
        {
                swap(a,0,i);
                a++;
                int m1 = EqDiv(a, l-1, SumI,SumE);
                a--;
                swap(a,0,i);
    
                *SumI = *SumI + a[i];
                *SumE = *SumE - a[i];
                swap(a,0,i);
                a++;
                int m2 = EqDiv(a,l-1, SumI,SumE);
                a--;
                swap(a,0,i);
                *SumI = *SumI - a[i];
                *SumE = *SumE + a[i];
    
                min = min3(min,m1,m2);
    
        }
        return min;
    

    }

    call the function with SumI =0 and SumE= sumof all the elements in a. This O(n!) solution does compute the way we can divide the given array into 2 parts such the difference is minimum. But definitely not practical due to the n! time complexity looking to improve this using DP.

提交回复
热议问题