Target Sum in C++


Suppose we have a list of non-negative integers, a1, a2, ..., an, and another value, that is target, S. Now we have 2 symbols + and -. For each integer, we should choose one from + and - as its new symbol. we have to find out how many ways to assign symbols to make sum of integers same as the target value S. So if the numbers are [1,1,1,1,1], and S = 3, then the output will be 5, as the combinations are – 1 + 1 + 1 + 1 + 1 = 3, + 1 – 1 + 1 + 1 + 1 = 3, + 1 + 1 – 1 + 1 + 1 = 3, + 1 + 1 + 1 – 1 + 1 = 3, + 1 + 1 + 1 + 1 – 1 = 3. So there are five ways to assign them.

To solve this, we will follow these steps −

  • Create one table dp of size 21 x 2001, fill this with – 1. This will be used for the dynamic programming approach
  • The recursive method will be used called solve(). This will take pos, array v, tempSum and the actual sum S. This will act like below −
  • if pos is same as size of array v, then return true, if s = tempSum, otherwise false
  • if dp[pos, tempSum + 1000] is not -1, then return dp[pos, tempSum + 1000]
  • ans := solve(pos + 1, v, tempSum – v[pos], s) + solve(pos + 1, v, tempSum + v[pos], s)
  • dp[pos, tempSum + 1000] = ans
  • return ans
  • call the solve() from main section using parameter solve(0, nums, 0, s)

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int dp[21][2001];
   int solve(int pos, vector <int> v, int tempSum, int s){
      if(pos == v.size()){
         return s == tempSum;
      }
      if(dp[pos][tempSum+1000]!=-1)return dp[pos][tempSum+1000];
      int ans = solve(pos+1,v,tempSum-v[pos],s) +solve(pos+1,v,tempSum+v[pos],s);
      dp[pos][tempSum+1000] = ans;
      return ans;
   }
   int findTargetSumWays(vector<int>& nums, int s) {
      int n = nums.size();
      if(s>1000)return 0;
      for(int i =0;i<21;i++){
         for(int j =0;j<2001;j++){
            dp[i][j] = -1;
         }
      }
      return solve(0,nums,0,s);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,1,1,1};
   cout << ob.findTargetSumWays(v, 3);
}

Input

[1,1,1,1,1]
3

Output

5

Updated on: 29-Apr-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements