题目描述:
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.
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.
给定非负数组和目标值s,对数组每个数都可以赋+或-,求有多少张赋值方法使得数组和等于s。采用深度优先搜索,传递对参数有nums,s,当前下标i,当前和sum,分别对nums[i]赋正值和负值,分别递归,直到遍历到数组末尾,判断sum是否等于s。
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum=0;
int i=0;
return DFS(nums,S,sum,i);
}
int DFS(vector<int>& nums, int S, int sum, int i)
{
int sum1=sum+nums[i];
int sum2=sum-nums[i];
if(i==(nums.size()-1))
{
int count=0;
if(sum1==S) count++;
if(sum2==S) count++;
return count;
}
return DFS(nums,S,sum1,i+1)+DFS(nums,S,sum2,i+1);
}
};
本文介绍了一个给定非负整数数组的问题,通过为数组中的每个元素分配加号或减号来实现目标和的方法数量。使用深度优先搜索算法解决此问题,并提供了一个C++实现示例。
512

被折叠的 条评论
为什么被折叠?



