Target Sum | Practice | GeeksforGeeks

Given an array of integers A[] of length N and an integer target.
You want to build an expression out of A by adding one of the symbols '+' and '-' before each integer in A and then concatenate all the integers.
For example, if arr = {2, 1}, you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that can be built, which evaluates to target.

Example 1:
Input:
N = 5
A[] = {1, 1, 1, 1, 1}
target = 3
Output:
5
Explanation:
There are 5 ways to assign symbols to 
make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3


Example 2:
Input:
N = 1
A[] = {1}
target = 1
Output:
1


Your Task:
The task is to complete the function findTargetSumWays() which finds and returns the number of different expressions that can be built.
 
Expected Time Complexity: O(N*sum), where sum refers to the range of sum possible.
Expected Auxiliary Space: O(N).
 
Constraints:
1 ≤ N ≤ 20
0 ≤ A[i] ≤ 1000
0 <= sum(A[i]) <= 104
-1000 <= target <= 1000
0
uratabhi3 weeks ago
class Solution { public:   int findTargetSumWays(vector<int>&A ,int target) {      int sum = std::accumulate(A.begin(), A.end(), 0);      if((target+sum)%2!=0) return 0;      int s1 =  (target+sum)/2;       vector<int> arr;        int zeros(0);        for(auto &i : A){             if(!i) zeros++;             else arr.push_back(i);        }      int n = int(arr.size());      int dp[n+1][s1+1];      memset(dp, -1, sizeof(dp));
      for(int i=0; i<=s1; i++){           dp[0][i] = 0;      }      for(int i=0; i<=n; i++){          dp[i][0] = 1;      }
      for(int i=1; i<=n; i++){         for(int j=1; j<=s1; j++){              if(arr[i-1]<=j){                  dp[i][j] = dp[i-1][j-arr[i-1]] + dp[i-1][j];              }              else{                  dp[i][j] = dp[i-1][j];              }         }      }     return (1<<zeros)*dp[n][s1];   }
0
gulshan991 month ago
class Solution {
  public:
    int dp[21][20001];
    int dfs(int index,vector<int>&A,int target,int sum)
    {
        if(index==A.size())return sum==target?1:0;
        if(dp[index][sum]!=-1)return dp[index][sum];
        int count=0;
        count+= dfs(index+1,A,target,sum+A[index]);
         count+= dfs(index+1,A,target,sum-A[index]);
        return dp[index][sum] = count;
    }
    int findTargetSumWays(vector<int>&A ,int target) {
        //Your code here
        memset(dp,-1,sizeof(dp));
        return dfs(0,A,target,0);
    }
};

+1
adityasingh1091 month ago
int findTargetSumWays(vector<int>&nums ,int target) {
        int sum=0;
        for(int i=0;i<nums.size();i++)
            sum=sum+nums[i];
            
        if (target<-sum || target>sum) 
            return 0;
            
        vector<vector<int>> dp(nums.size() + 1, vector<int>(sum*2 + 1, 0));
        //int dp[nums.size()+1][sum*2+1];
        dp[0][sum]=1;
        for(int i=1;i<=nums.size();i++)
        {
            for(int j=0;j<sum*2+1;j++)
            {
                if(j+nums[i-1]<sum*2+1)
                    dp[i][j]=dp[i][j]+dp[i-1][j+nums[i-1]];
                if(j-nums[i-1]>=0)
                    dp[i][j]=dp[i][j]+dp[i-1][j-nums[i-1]];
            }
        }
        return dp[nums.size()][sum+target];
    }
0
ar08051 month ago
LOGIC USED

Let Two Subset be S1 and S2,Whose difference is equal to target as given in question.
Now

S1-S2=Target (1)

S1+S2=Total_Sum_Of_Array (2)

Subtracting Equation 1 from Equation 2.We will get:

2*S2 = Total_Sum_Of_Array-Target

Now Total_Sum_Of_Array-Target have to Even as it is equal to 2*S2 if It not Even return 0.

Now Applying Logic of Subset sum equal to given sum Logic where Target is S2,We will get Our count(Ans).

class Solution {
public:
    
    int count(vector<int>& v, int tar,int n,vector<vector<int>>&t)
    {
        
        if(n==0 and tar==0)
        {
            return 1;
        }
        if(n==0)
        {
            return 0;
        }
        if(t[n][tar]!=-1)
        {
            return t[n][tar];
        }
        
        if(v[n-1]<=tar)
        {
            return(t[n][tar]=count(v,tar-v[n-1],n-1,t) + count(v,tar,n-1,t));
        }
        else
        {
            return(t[n][tar]=count(v,tar,n-1,t));
        }
        
        
        
    }
    
    
    
    int findTargetSumWays(vector<int>& nums, int target) {
        
        int sum=accumulate(nums.begin(),nums.end(),0);
        
        
       
        int dif = (sum-target);
        if(target>sum || (dif)%2!=0)
        {
            return 0;
        }
        vector<vector<int>>t(nums.size()+1,vector<int>((dif)/2+1,-1));
       
        return(count(nums,(dif)/2,nums.size(),t));
        
    }
};
-1
sougataroy8932 months ago
c++
int find(vector<int> a,int n,int t){       if(n==0 && t==0) return 1;       if(n==0) return 0;       return find(a,n-1,t-a[n-1])+find(a,n-1,t+a[n-1]);   }   int findTargetSumWays(vector<int>&A ,int target) {       return find(A,A.size(),target);   }
0
darsisriguruaakash2 months ago
class Solution:
   def findTargetSumWays(self, arr, N, target):
       # code here 
       sum_in = sum(arr)
       sum_to = (target+sum_in)
       if sum_to%2 != 0:
           return 0
       sum_to //=2
       dp = [[0 for i in range(sum_to+1)] for i in range(N+1)]
       for i in range(N+1):
           dp[i][0] = 1 
       for i in range(1,sum_to+1):
           dp[0][i] = 0 
       
       for i in range(1,N+1):
           for j in range(1,sum_to+1):
               if arr[i-1]>j:
                   dp[i][j] = dp[i-1][j]
               else:
                   dp[i][j] = dp[i-1][j]+dp[i-1][j-arr[i-1]]
       return dp[N][sum_to]

0
shariprakash3382 months ago
DP Solution 
Similiar to O(1) Knapsack type:  counting target sum till Subset of any + ve or -ve taken having subset sum till (Sum+target)/2
class Solution { public:   int findTargetSumWays(vector<int>&A ,int target) {       int sum = 0;       int n = A.size();       for(int i = 0;i<A.size();i++){           sum += A[i];        }       if((sum+target)%2!=0) return 0;              int new_target = (sum + target)/2;              int dp[n+1][new_target+1];       for(int i = 0;i<=n;i++){           for(int j = 0;j<=new_target; j++){               if(j==0) dp[i][j] = 1;               else if(i==0) dp[i][j] = 0;               else if(A[i-1]>j){                   dp[i][j] = dp[i-1][j];               }               else{                   dp[i][j] = dp[i-1][j] + dp[i-1][j-A[i-1]];               }           }       }       return dp[n][new_target];   }};
 
-1
code_rama3 months ago
static int findTargetSumWays(int[] arr , int N, int target) {       // code here       int arraysum = 0;       int zeroes = 0;       for(int i = 0; i < N; i++){           arraysum += arr[i];                  }              if((target + arraysum) % 2 == 1){           return 0;       }       int sum = (target + arraysum) / 2;       sum = Math.abs(sum);       int dp[][] = new int[N + 1][sum + 1];       for(int i = 0; i <= N; i++){           dp[i][0] = 1;       }       for(int i = 1; i <= N; i++){           for(int j = 1; j <= sum; j++){               if(arr[i - 1] <= j){                   dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j];               }else{                   dp[i][j] = dp[i - 1][j];               }           }       }       return dp[N][sum];   }
+20
mukulbansal4213 months ago
Aditya verma OP
0
sandeep55213 months ago
C++ 10 lines DP Solution.
class Solution {
 public:
   map<pair<int,int>,int> mp;
   int func(vector<int> v,int n,int tar)
   {
       if(!n and !tar) return 1;
       if(!n) return 0;
       if(mp.find({n,tar})!=mp.end())
           return mp[{n,tar}];
       mp[{n,tar}]=func(v,n-1,tar+v[n-1])+func(v,n-1,tar-v[n-1]);
       return mp[{n,tar}];
   }
   int findTargetSumWays(vector<int>&A ,int target) {
       return func(A,A.size(),target);
   }
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.