week14
题目
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.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
原题地址:https://leetcode.com/problems/target-sum/description/
解析
题目给定一组数和指定的目标和,每个数前面的符号可正可负,求出有多少种不同的符号组合能使这组数与目标和相等。
大致思路是采用深度优先的思想,采用一棵树,根节点为0,从第二层的两个节点分别为第一个数取正和取负,从第二层开始,每个节点的两个子节点分别为其下一个数取正和取负,叶子结点为最后一个数。然后采用深度优先搜素遍历该树,每次遍历到叶子结点可以得到一个和,将其与目标和进行比较。最后得到与目标和相等的组合的个数即为答案。
代码
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
if (nums.size() == 0) {
return 0;
}
int present = 0;
int count = 0;
int sum = 0;
recursiveFind(nums, S, present, sum, count);
return count;
}
void recursiveFind(vector<int>& nums, int S, int& present, int& sum, int& count) {
/* 遍历到最后一个数 */
if (present == nums.size() - 1) {
if (nums[present] + sum == S) {
++count;
}
if (sum - nums[present] == S) {
++count;
}
}
/* 未到最后一个数,选定当前的数的符号,递归遍历下一个数 */
else {
sum += nums[present];
++present;
recursiveFind(nums, S, present, sum, count);
--present;
sum -= (2 * nums[present]);
++present;
recursiveFind(nums, S, present, sum, count);
--present;
sum += nums[present];
}
}
};