-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathPartitionEqualSubsetSum.cpp
97 lines (75 loc) · 2.74 KB
/
PartitionEqualSubsetSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// https://leetcode.com/problems/partition-equal-subset-sum/description/
class Solution {
public:
// Simple Recursive Solution
// bool solve(vector<int>& nums, int index, int target){
// if(index>=nums.size())
// return false;
// if(target==0)
// return true;
// if(target<0)
// return false;
// bool include= solve(nums, index+1, target-nums[index]);
// bool exclude= solve(nums, index+1, target);
// return include || exclude;
// }
// Recursion + Memoization (Top-Down Approach)
// bool solve(vector<int>& nums, int index, int target, vector<vector<int>>& dp){
// if(index>=nums.size())
// return false;
// if(target==0)
// return true;
// if(target<0)
// return false;
// if(dp[index][target]!=-1)
// return dp[index][target];
// bool include= solve(nums, index+1, target-nums[index], dp);
// bool exclude= solve(nums, index+1, target, dp);
// dp[index][target]= include||exclude;
// return dp[index][target];
// }
// Tabulation Approach (Bottom-Up Approach)
// bool solve(vector<int>& nums, int target){
// vector<vector<int>> dp(nums.size()+1, vector<int>(target+1, 0));
// for(int i=0; i<=nums.size(); i++)
// dp[i][0]= 1;
// for(int index=nums.size()-1; index>=0; index--){
// for(int t=0; t<=target; t++){
// bool include= false;
// if(t-nums[index]>=0)
// include= dp[index+1][t-nums[index]];
// bool exclude= dp[index+1][t];
// dp[index][t]= include||exclude;
// }
// }
// return dp[0][target];
// }
bool solve(vector<int>& nums, int target){
vector<int> curr(target+1, 0);
vector<int> next(target+1, 0);
next[0]= 1;
for(int index=nums.size()-1; index>=0; index--){
for(int t=0; t<=target; t++){
bool include= false;
if(t-nums[index]>=0)
include= next[t-nums[index]];
bool exclude= next[t];
curr[t]= include||exclude;
}
next= curr;
}
return next[target];
}
bool canPartition(vector<int>& nums) {
int total= 0;
for(auto i : nums)
total+= i;
if(total%2!=0)
return false;
// Simple Recursive Solution
// return solve(nums, 0, total/2);
// vector<vector<int>> dp(nums.size()+1, vector<int>((total/2)+1, -1));
// return solve(nums, 0, total/2, dp);
return solve(nums, total/2);
}
};