The problem I'm solving is given as follows:
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.
Here is my solution:
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
return findTargetSum(nums, 0, S, 0);
}
int findTargetSum(vector<int>& nums, int i , int S, int sumSoFar){
if(i == nums.size()){
return sumSoFar == S;
}
return findTargetSum(nums, i + 1, S, sumSoFar + nums[i]) + findTargetSum(nums, i + 1, S, sumSoFar - nums[i]);
}
};
This solution however performs slower than the target. I suspect there may be some DP solution I am missing or maybe some optimization in my current solution might be to blame. Any advice on how to cut the run time would be appreciated.