Introduction:
In this tutorial we are going to solve a problem "Target Sum" which is from leetcode. and believe me it's really a good problem to understand Backtracking(Recursion). and if you try to understand the problem as well as code you will get a clear picture of Backtracking.
Problem Statement: Link To Problem
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols
+
and -
. For each integer, you should choose one from +
and -
as its new symbol.Find out how many ways to assign symbols to make sum of integers equal to target S.
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-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
There are 5 ways to assign symbols to make the sum of nums be target 3.
Solution:
As given in question, we have two operation + and -. so we will make recursive
call for + and - . and if we have sum as target and we have reached upto the last
index then we will increase count.
Full Code:
int count=0;
void helper(vector<int>& nums, int i, int ans, int s){
if(ans==s && i==nums.size()){
count++;
}
if(i==nums.size())
return ;
helper(nums,i+1,ans+nums[i],s);
helper(nums,i+1,ans-nums[i],s);
}
int findTargetSumWays(vector<int>& nums, int S) {
if(nums.size()==0)
return false;
helper(nums,0,0,S);
return count;
}
Conclusion:
This is really a good problem to practice backtracking. and just do a dry run on paper and you will
get things in very clear way. if still have any query, then comment it down.
Comments
Post a Comment