Partition Equal Subset Sum in C++


Suppose we have a non-empty array containing only positive numbers, we have to find if the array can be partitioned into two subsets such that the sum of elements in both subsets is the same. So if the input is like [1,5,11,5], the output will be true. As this array can be partitioned as [1, 5, 5] and [11]

To solve this, we will follow these steps −

  • n := size of the array
  • sum := 0
  • for i := 0 to n – 1
    • sum := sum + nums[i]
  • if sum is odd, return false
  • sum := sum / 2
  • create one array called dp of size sum + 1
  • dp[0] := true
  • for i in range 0 to n – 1
    • x := nums[i]
    • for j := sum down to j – x
      • dp[j] := dp[j] or dp[j - x], which is not 0
  • return dp[sum]

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool canPartition(vector<int>& nums) {
      int n = nums.size();
      int sum = 0;
      for(int i =0;i<n;i++)sum+=nums[i];
      if(sum&1)return false;
      sum/=2;
      vector <bool> dp(sum+1);
      dp[0] = true;
      for(int i =0;i<n;i++){
         int x = nums[i];
         for(int j =sum;j-x>=0;j--){
            dp[j]=dp[j] || dp[j-x];
         }
      }
      return dp[sum];
   }
};
main(){
   Solution ob;
   vector<int> v = {1,5,11,5};
   cout << ob.canPartition(v);
}

Input

[1,5,11,5]

Output

1

Updated on: 28-Apr-2020

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements