fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Solution {
  6. public:
  7. void calculateWays(vector<int>& nums, int index, int currentSum, int target, int& totalWays) {
  8. // Base case: when we've considered all numbers
  9. if (index == nums.size()) {
  10. if (currentSum == target) {
  11. totalWays++;
  12. }
  13. return;
  14. }
  15. // Include the current number with + and - sign
  16. calculateWays(nums, index + 1, currentSum + nums[index], target, totalWays);
  17. calculateWays(nums, index + 1, currentSum - nums[index], target, totalWays);
  18. }
  19.  
  20. int findTargetSumWays(vector<int>& nums, int target) {
  21. int totalWays = 0;
  22. calculateWays(nums, 0, 0, target, totalWays);
  23. return totalWays;
  24. }
  25. };
  26.  
  27. int main() {
  28. // Example input
  29. vector<int> nums = {1, 1, 1, 1, 1};
  30. int target = 3;
  31.  
  32. // Create an object of Solution and call the method
  33. Solution solution;
  34. int result = solution.findTargetSumWays(nums, target);
  35.  
  36. // Output the result
  37. cout << "Number of ways to reach target " << target << ": " << result << endl;
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Number of ways to reach target 3: 5