-
Notifications
You must be signed in to change notification settings - Fork 9
/
PartitionEqualSubsetSum.cpp
34 lines (29 loc) · 1.03 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
// Problem: https://leetcode.com/problems/partition-equal-subset-sum/
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class PartitionEqualSubsetSum {
public:
bool canPartition(vector<int>& nums) {
int sum = getSum(nums);
unordered_map<string, bool> dp;
if ((sum % 2) == 1) return false;
return canPartitionUtil(nums, nums.size() - 1, sum / 2, dp);
}
bool canPartitionUtil(vector<int>& nums, int index, int target, unordered_map<string, bool>& dp) {
if (target == 0) return true;
if (target < 0 || index < 0) return false;
string key = to_string(index) + ":" + to_string(target);
if (dp.find(key) != dp.end()) return dp[key];
dp[key] =
canPartitionUtil(nums, index - 1, target - nums[index], dp) ||
canPartitionUtil(nums, index - 1, target, dp);
return dp[key];
}
int getSum(vector<int>& nums) {
int sum = 0;
for (int elem : nums) sum += elem;
return sum;
}
};