Skip to content

Commit c33ceda

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 3ae7a7c commit c33ceda

File tree

1 file changed

+53
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)