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 −
Let us see the following implementation to get a better understanding −
#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); }
[1,1,1,1,1] 3
5