|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive helper function to check if we can partition the array into two subsets |
| 4 | + int solve(vector<int>& nums, int index, int n, int target) { |
| 5 | + // Base case: If the index exceeds the array size, return 0 (no valid partition) |
| 6 | + if(index >= n) return 0; |
| 7 | + |
| 8 | + // If the target becomes negative, return 0 (not possible to partition) |
| 9 | + if(target < 0) return 0; |
| 10 | + |
| 11 | + // If the target becomes zero, it means we've found a valid partition (return 1) |
| 12 | + if(target == 0) return 1; |
| 13 | + |
| 14 | + // Option 1: Include the current element and try to partition with the reduced target |
| 15 | + int include = solve(nums, index+1, n, target - nums[index]); |
| 16 | + |
| 17 | + // Option 2: Exclude the current element and try to partition without changing the target |
| 18 | + int exclude = solve(nums, index+1, n, target - 0); |
| 19 | + |
| 20 | + // Return true if either including or excluding the current element leads to a valid partition |
| 21 | + return include or exclude; |
| 22 | + } |
| 23 | + |
| 24 | + // Main function to check if we can partition the array into two subsets with equal sum |
| 25 | + bool canPartition(vector<int>& nums) { |
| 26 | + int total = 0; |
| 27 | + |
| 28 | + // Calculate the total sum of the elements in the array |
| 29 | + for(auto & num : nums) total += num; |
| 30 | + |
| 31 | + // If the total sum is odd, we cannot partition it into two equal subsets |
| 32 | + if(total & 1) return 0; |
| 33 | + |
| 34 | + // Set the target as half of the total sum |
| 35 | + int target = total / 2; |
| 36 | + |
| 37 | + // Call the solve function to check if we can find a subset that sums to 'target' |
| 38 | + return solve(nums, 0, nums.size(), target); |
| 39 | + } |
| 40 | +}; |
0 commit comments