|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to check if a subset sum equal to 'target' exists using dynamic programming |
| 4 | + int solve(vector<int>& nums, int n, int target) { |
| 5 | + // dp[i][j] will store whether it's possible to form sum 'j' using the first 'i' elements |
| 6 | + vector<vector<int>> dp(n+1, vector<int>(target+1, 0)); |
| 7 | + |
| 8 | + // Base case: sum of 0 can always be formed (empty subset) |
| 9 | + for(int i = 0; i <= n; i++) dp[i][0] = 1; |
| 10 | + |
| 11 | + // Fill the dp table in bottom-up manner |
| 12 | + // Iterate over all indices of nums in reverse (from n-1 to 0) |
| 13 | + for(int index = n-1; index >= 0; index--) { |
| 14 | + // Iterate over all possible target sums from 1 to the desired target sum |
| 15 | + for(int t = 1; t <= target; t++) { |
| 16 | + int include = 0; |
| 17 | + // If the current number can be included (i.e., target - nums[index] >= 0) |
| 18 | + if(t - nums[index] >= 0) include = dp[index+1][t - nums[index]]; |
| 19 | + |
| 20 | + // Exclude the current element (i.e., use the result from the next index with the same target) |
| 21 | + int exclude = dp[index+1][t]; |
| 22 | + |
| 23 | + // The result for dp[index][t] is the logical OR of including or excluding the element |
| 24 | + dp[index][t] = include or exclude; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // The final result is stored at dp[0][target], which tells if the target sum can be achieved |
| 29 | + return dp[0][target]; |
| 30 | + } |
| 31 | + |
| 32 | + // Main function to check if we can partition the array into two subsets with equal sum |
| 33 | + bool canPartition(vector<int>& nums) { |
| 34 | + int n = nums.size(); |
| 35 | + int total = 0; |
| 36 | + |
| 37 | + // Calculate the total sum of the elements in the array |
| 38 | + for(auto & num : nums) total += num; |
| 39 | + |
| 40 | + // If the total sum is odd, it can't be partitioned into two equal subsets |
| 41 | + if(total & 1) return 0; |
| 42 | + |
| 43 | + // Set the target as half of the total sum |
| 44 | + int target = total / 2; |
| 45 | + |
| 46 | + // Call the solve function to check if a subset with sum equal to 'target' exists |
| 47 | + return solve(nums, n, target); |
| 48 | + } |
| 49 | +}; |
0 commit comments