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.
Example 1:
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.这一题可以用分治算法来解决。
第一个符号可以为:+ 和 -
第二个符号亦同,可以为+和-。那么和第一个符号可以组成++、+-、-+、--
如此进行下去,可构成一棵递归树。
我们设一个函数用来执行递归。令和初始化为sum=0,每递归一次,记录递归的次数i。每一层递归,要么sum += nums[i],要么sum -= nums[i]
直到i = nums.size(),查看是否和target相等。
代码如下:
class Solution {
public:
int count = 0;
int target;
void DP(vector<int>& nums, int sum, int i){
if (i < nums.size()){
DP(nums, sum+nums[i], i+1);
DP(nums, sum-nums[i], i+1);
}
else{
if (sum == target) count++;
}
}
int findTargetSumWays(vector<int>& nums, int S) {
target = S;
DP(nums, 0, 0);
return count;
}
};