Subset Sum
Given a set of non negative numbers and a total, find if there exists a subset in this set whose sum is same as total.
Example:
- Partition Equal Subset Sum
Target Sum (Medium)
Algorithm:
Firstly this algorithm can be viewed as knapsack problem where individual array elements are the weights and half the sum as total weight of the knapsack.
take a solution array as boolean array sol[] of size sum/2+1
For each array element,traverse the array and set sol [j] to be true if sol [j – value of array] is true
Let halfsumcloser be the closest reachable number to half the sum and partition are sum-halfsumcloser and halfsumcloser.
start from halfsum and decrease halfsumcloser once everytime until you find that sol[halfsumcloser] is true
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for (int n : nums) sum += n;
if (sum % 2) return false;
int target = sum >> 1;
vector<bool> dp(target+1, false);
dp[0] = true;
for (int n : nums) {
for (int i = target; i >= n; --i) {
if (dp[i-n]) dp[i] = true;
}
}
return dp[target];
}
};