#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void calculateWays(vector<int>& nums, int index, int currentSum, int target, int& totalWays) {
// Base case: when we've considered all numbers
if (index == nums.size()) {
if (currentSum == target) {
totalWays++;
}
return;
}
// Include the current number with + and - sign
calculateWays(nums, index + 1, currentSum + nums[index], target, totalWays);
calculateWays(nums, index + 1, currentSum - nums[index], target, totalWays);
}
int findTargetSumWays(vector<int>& nums, int target) {
int totalWays = 0;
calculateWays(nums, 0, 0, target, totalWays);
return totalWays;
}
};
int main() {
// Example input
vector<int> nums = {1, 1, 1, 1, 1};
int target = 3;
// Create an object of Solution and call the method
Solution solution;
int result = solution.findTargetSumWays(nums, target);
// Output the result
cout << "Number of ways to reach target " << target << ": " << result << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY2xhc3MgU29sdXRpb24gewpwdWJsaWM6CiAgICB2b2lkIGNhbGN1bGF0ZVdheXModmVjdG9yPGludD4mIG51bXMsIGludCBpbmRleCwgaW50IGN1cnJlbnRTdW0sIGludCB0YXJnZXQsIGludCYgdG90YWxXYXlzKSB7CiAgICAgICAgLy8gQmFzZSBjYXNlOiB3aGVuIHdlJ3ZlIGNvbnNpZGVyZWQgYWxsIG51bWJlcnMKICAgICAgICBpZiAoaW5kZXggPT0gbnVtcy5zaXplKCkpIHsKICAgICAgICAgICAgaWYgKGN1cnJlbnRTdW0gPT0gdGFyZ2V0KSB7CiAgICAgICAgICAgICAgICB0b3RhbFdheXMrKzsgCiAgICAgICAgICAgIH0KICAgICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICAvLyBJbmNsdWRlIHRoZSBjdXJyZW50IG51bWJlciB3aXRoICsgYW5kIC0gc2lnbgogICAgICAgIGNhbGN1bGF0ZVdheXMobnVtcywgaW5kZXggKyAxLCBjdXJyZW50U3VtICsgbnVtc1tpbmRleF0sIHRhcmdldCwgdG90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