Balanced partition

后端 未结 3 763
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 19:47

I know this was talked over a lot here, but I am struggling with this problem.

We have a set of numbers, e.g [3, 1, 1, 2, 2, 1], and we need to break it into two sub

3条回答
  •  失恋的感觉
    2020-12-16 20:15

    This will be O(2^N). No Dynamic Programming used here. You can print result1, result2 and difference after execution of the function. I hope this helps.

    vector p1,p2;
    vector result1,result2;
    vector array={12,323,432,4,55,223,45,67,332,78,334,23,5,98,34,67,4,3,86,99,78,1};
    
    void partition(unsigned int i,long &diffsofar, long sum1,long sum2)
    {
        if(i==array.size())
        {
            long diff= abs(sum1 - sum2);
            if(diffsofar > diff)
            {
                result1 =  p1;
                result2 = p2;
                diffsofar = diff;
            }
            return;
        }
    
        p1.push_back(array[i]);
        partition(i+1,diffsofar,sum1+array[i],sum2);
        p1.pop_back();
    
        p2.push_back(array[i]);
        partition(i+1,diffsofar,sum1,sum2+array[i]);
        p2.pop_back();
    
        return;
    }
    

提交回复
热议问题