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:

  1. Partition Equal Subset Sum
  2. Target Sum (Medium)

  3. Balanced Partition Problem

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.

  1. take a solution array as boolean array sol[] of size sum/2+1

  2. For each array element,traverse the array and set sol [j] to be true if sol [j – value of array] is true

  3. Let halfsumcloser be the closest reachable number to half the sum and partition are sum-halfsumcloser and halfsumcloser.

  4. 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];
    }
};

results matching ""

    No results matching ""