题目:
You are given an integer array nums
and an integer target
.
You want to build an expression out of nums by adding one of the symbols '+'
and '-'
before each integer in nums and then concatenate all the integers.
- For example, if
nums = [2, 1]
, you can add a'+'
before2
and a'-'
before1
and concatenate them to build the expression"+2-1"
.
Return the number of different expressions that you can build, which evaluates to target
.
Example 1:
Input: nums = [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: nums = [1], target = 1 Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
思路1:
转化成dp中的背包问题,这个转化过去比较难想。首先一堆数字,里面肯定有一堆要是加上负号的,称为A,一堆要是正的,称为B,A+B=sum,即数组总和,sum一定是正数,因为题目给的数组里面值都大于等于0。那么我们其实我们要做的就是使B - A = target即可,代入为 ,这里显然sum和target都是定值,转化一下即可求出B:。这里有几个点要注意,首先如果sum+target是个奇数,那么B肯定是不成立的,应该返回0;另一个是如果target比sum还要大,那怎么都不可能达到,也要返回0。到这里已经可以转化成背包问题了,背包总重量是B,dp[ j ]表示和为 j 的方法有几种。转移公式应该是dp[j] += dp[j - nums[i]],比如我已经有了dp[3],并且当前nums[i] = 2,那么dp[5]的其中一些方法就来自于dp[5 - 2]即dp[3]。最后返回dp[B]即可。
代码1:
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = accumulate(begin(nums), end(nums), 0);
target = abs(target);
if ((sum + target) & 1 || target > sum)
return 0;
int bag = (sum + target) / 2;
vector<int> f(bag + 1);
f[0] = 1;
for (int i = 0; i < nums.size(); i++) {
for (int j = bag; j >= nums[i]; j--) {
f[j] += f[j - nums[i]];
}
}
return f[bag];
}
};
思路2:
第二种方法是回溯法,因为nums长度最大为20,可以暴力搜索出来。对于nums每一位,选择无非是加上或者减去,当遍历完数组后,如果答案等于target,则记录,最后返回记录的那个值即可。
代码2:
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
dfs(nums, 0, 0, target);
return count;
}
private:
int count = 0;
void dfs(vector<int>& nums, int index, int cur, int target) {
if (index == nums.size()) {
if (cur == target)
count++;
return;
}
dfs(nums, index + 1, cur + nums[index], target);
dfs(nums, index + 1, cur - nums[index], target);
}
};