Advertisement
imashutosh51

Partition Equal Subset Sum

Jul 25th, 2022
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //TC O(N*W) w=sum of whole array.
  2. //created a dp where column contains sum from 0 to total sum of array
  3. //and row contains elements of all the array,oth row means no elements selected
  4. //logic is simple,either include the curretn element or not
  5. class Solution {
  6. public:
  7.     bool canPartition(vector<int>& arr) {
  8.         int sum=0,n=arr.size();
  9.         for(int i=0;i<n;i++) sum+=arr[i];    //found sum of all the items ie. j or column of dp aray
  10.         if(sum%2!=0) return false;
  11.         bool dp[n+1][sum+1];
  12.         for(int i=0;i<=n;i++){
  13.             for(int j=0;j<=sum;j++){
  14.                 if(j==0){dp[i][j]=true;}    //0 weight is possible to have without including any item
  15.                 else if(i==0){dp[i][j]=false;} //all the weight from 1 to sum can't be possible with no items
  16.                 else if(arr[i-1]>j){     //if current array element is greater than the j weight,
  17.                     dp[i][j]=dp[i-1][j];  //then it can't be included.
  18.                 }
  19.                 else{             //if current array element is smaller than current weight,then either it can be included
  20.                     dp[i][j]=dp[i-1][j] || dp[i-1][j-arr[i-1]];  //or not incuded.
  21.                 }
  22.             }
  23.         }
  24.         return dp[n][sum/2];    //check for half sum is possible or not?
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement