Skip to content

Commit 704851c

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 05471bf commit 704851c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
// Recursive function with memoization to check if a subset sum equals the target
4+
int solve(vector<int>& nums, int index, int n, int target, vector<vector<int>> &dp) {
5+
// Base case: If we've processed all elements and haven't reached the target, return 0
6+
if(index >= n) return 0;
7+
8+
// If the target becomes negative, return 0 (we can't have a negative sum)
9+
if(target < 0) return 0;
10+
11+
// If the target becomes zero, it means we've found a subset whose sum equals the target
12+
if(target == 0) return 1;
13+
14+
// Check if the result for this subproblem has already been computed
15+
if(dp[index][target] != -1) return dp[index][target];
16+
17+
// Option 1: Include the current element (nums[index]) in the subset and reduce the target
18+
int include = solve(nums, index + 1, n, target - nums[index], dp);
19+
20+
// Option 2: Exclude the current element and try the next index with the same target
21+
int exclude = solve(nums, index + 1, n, target, dp);
22+
23+
// Memoize the result for the current index and target
24+
return dp[index][target] = include or exclude; // Use logical OR to check if either option works
25+
}
26+
27+
// Main function to check if we can partition the array into two subsets with equal sum
28+
bool canPartition(vector<int>& nums) {
29+
int n = nums.size();
30+
int total = 0;
31+
32+
// Calculate the total sum of the elements in the array
33+
for(auto & num : nums) total += num;
34+
35+
// If the total sum is odd, return false because it can't be partitioned into two equal subsets
36+
if(total & 1) return 0;
37+
38+
// Set the target as half of the total sum
39+
int target = total / 2;
40+
41+
// Create a memoization table to store results for subproblems
42+
// dp[i][j] will store whether it's possible to form sum 'j' using the first 'i' elements
43+
vector<vector<int>> dp(n, vector<int>(target + 1, -1));
44+
45+
// Call the recursive function to check if a subset sum equal to 'target' exists
46+
return solve(nums, 0, n, target, dp);
47+
}
48+
};

0 commit comments

Comments
 (0)