Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
Solution : (Recursion)
classSolution{public:boolsubsetSum(vector<int> v,int sum,int pos) {if(pos ==v.size()){returnfalse; }if (sum ==0) {returntrue; }if (subsetSum(v, sum -v[pos], pos +1) ||subsetSum(v, sum, pos +1)) {returntrue; }returnfalse; }boolcanPartition(vector<int> &nums) {int s =0;for (int i =0; i <nums.size(); i++) { s = s +nums[i]; } // Checking if solution exitsif (s %2==0) { //Subset sum(Finding a subset with given sum)if (subsetSum(nums, s /2,0)) {returntrue; }returnfalse; }returnfalse; }};
Time Complexity: O(2^n)
Solution : (DP)
classSolution{public:boolsubsetSum(vector<int> nums,int target) { vector<vector<bool>>v(nums.size() +1,vector<bool>(target +1,0));v[0][0] =true;for (int i =1; i <=nums.size(); i++) {int cur =nums[i -1];for (int j =0; j <= target; j++) {if (j < cur) {v[i][j] =v[i -1][j]; }else {v[i][j] =v[i -1][j] ||v[i -1][j - cur]; } } }returnv[nums.size()][target]; }boolcanPartition(vector<int> &nums) {int s =0;for (int i =0; i <nums.size(); i++) { s = s +nums[i]; }if (s %2==0) { //Subset sum(Finding a subset with given sum)if (subsetSum(nums, s /2)) {returntrue; }returnfalse; }returnfalse; }};
Time Complexity: O(n * m)
Space Complexity: O(n * m)