494. Target Sum

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:

1
2
3
4
5
6
7
8
9
10
11
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.

Note:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

暴力破解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
if(nums.empty()){
return S == 0 ? 1 : 0;
}
return dfs(nums, S, 0, 0);
}
int dfs(vector<int>& nums, int S, int index, int sum){
if(index == nums.size()){
return sum == S ? 1 : 0;
}
return dfs(nums, S, index + 1, sum + nums[index]) + dfs(nums, S, index + 1, sum - nums[index]);
}
};

自顶向下的记忆化搜索

这里会涉及到负值,如何处理呢?加上可能的最小值的负数,进行偏移.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
if(nums.empty()){
return S == 0 ? 1 : 0;
}
int sum = 0;
vector<vector<int>> res(nums.size(), vector<int>(2010, -1));
return dfs(nums, S, 0, 0, res);
}
int dfs(vector<int>& nums, int S, int index, int sum, vector<vector<int>>& res){
if(index == nums.size()){
return sum == S ? 1 : 0;
}
if(res[index][sum + 1000]!=-1){
return res[index][sum + 1000];
}
int add = dfs(nums, S, index + 1, sum + nums[index], res);
int sub = dfs(nums, S, index + 1, sum - nums[index], res);
res[index][sum + 1000] = add + sub;
return add + sub;
}
};

自底向上

dp[i][j]表示到第i个元素,组成的和为j的方法数.
dp[i][sum + nums[i]] = dp[i][sum + nums[i]] + dp[i-1][sum]