Target Sum
来源:互联网 发布:淘宝助手是什么 编辑:程序博客网 时间:2024/06/05 02:28
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: 5Explanation: -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 = 3There 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.
题目意思为寻找给定数组的一个全部为正的子集A,以及该子集的补集B,满足子集A中所有元素的和减去子集B中所有元素的和等于target的值。
我们首先建立一个函数sum(vector<int>& nums),计算某一数组元素的和。
将问题进行转换,根据我们的分析
sum(A)-sum(B)=target
sum(A)+sum(B)+sum(A)-sum(B)=target+sum(A)+sum(B)
2*sum(A)=target+sum(nums)
所以我们的任务是寻找这样一个数组的子集,该子集满足2*sum(A)=target+sum(nums)
函数部分设计如下:
int findTargetSumWays(vector<int>& nums, int s) {
int sum = accumulate(nums.begin(), nums.end(), 0);return sum < s || (s + sum) & 1 ? 0 : subsetSum(nums, (s + sum) >> 1);
}
int subsetSum(vector<int>& nums, int s) {
int dp[s + 1] = { 0 };
dp[0] = 1;
for (int n : nums)
for (int i = s; i >= n; i--)
dp[i] += dp[i - n];
return dp[s];
}
测试正确
阅读全文
0 0
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- Target Sum
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- 494. Target Sum
- leetcode_middle_15_494. Target Sum
- [leetcode]494. Target Sum
- 494. Target Sum
- IPtables 学习笔记一
- 关于C++中的mutable关键字的研究
- IPtables 学习笔记二
- Android开发心得(一)
- JAVA中的运算符的总结
- Target Sum
- IPtables 学习笔记三
- 程序猿的爱情,猿粪是一个奇妙的东西
- [bzoj4810][Ynoi2017]由乃的玉米田 bitset+莫队
- 图结构练习——BFS——从起始点到目标点的最短步数
- Xception —— 深度可分卷积
- j2ee的web项目,在浏览器中发起一个该项目中html页面的绝对地址,也是发起的一个http url请求,请求的响应报文的结果就是该html页面的所有html代码
- 变长参数函数(转载)
- IPtables学习笔记四