Subset Sum - C++ Solution

1. Introduction

This blog post explores a variant of the subset sum problem, a classic problem in computer science and combinatorics. The objective is to find the total number of ways to reach a specified target sum using only addition and subtraction operators on elements of an integer array.

Problem

Given an integer array, we need to determine the total number of ways to calculate a specified target sum using only the addition and subtraction operators. Each element in the array can be used once and is involved in the sum with either a positive or negative sign.

2. Solution Steps

1. Utilize dynamic programming to explore all possible sums.

2. Maintain a count of the number of ways to achieve each possible sum.

3. Traverse the array and update the count for each element.

4. Finally, return the count corresponding to the target sum.

3. Code Program

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int subsetSumWays(const vector<int>& nums, int target) {
    unordered_map<int, int> dp = {{0, 1}};
    for (int num : nums) {
        unordered_map<int, int> temp;
        for (auto& p : dp) {
            temp[p.first + num] += p.second;
            temp[p.first - num] += p.second;
        }
        dp = temp;
    }
    return dp[target];
}

int main() {
    vector<int> nums = {5, 3, -6, 2};
    int target = 6;
    cout << "Number of ways to calculate " << target << ": " << subsetSumWays(nums, target) << endl;
    return 0;
}

Output:

Number of ways to calculate 6: 4

Explanation:

The function subsetSumWays uses a dynamic programming approach to compute the number of ways to achieve the target sum. It iteratively builds up a map of all possible sums that can be achieved using the elements seen so far, along with their counts. For each element in the array, it updates the map to include sums that include the current element, both positively and negatively. For the input array [5, 3, -6, 2] with a target of 6, there are 4 different ways to achieve this sum using addition and subtraction.


Comments