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 −
Let us see the following implementation to get a better understanding −
#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); }
[1,5,11,5]
1