(LeetCode) 494. Target Sum
来源:互联网 发布:广告联盟js代码 编辑:程序博客网 时间:2024/06/01 10:35
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:
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.
代码
class Solution {public: int findTargetSumWays(vector<int>& nums, int S) { int sum = accumulate(nums.begin(), nums.end(), 0); return recursive(nums, S, 0, nums.size()-1, sum); } int recursive(vector<int>& nums, int S, int left, int right, int sum){ if (sum<abs(S)) return 0; if (left==right) return (S==nums[left])+(S==-nums[left]); return recursive(nums, S-nums[left], left+1, right, sum-nums[left])+recursive(nums, S+nums[left], left+1, right, sum-nums[left]); }};
阅读全文
0 0
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- [leetcode]494. Target Sum
- Leetcode 494. Target Sum
- Leetcode-494. Target Sum
- Leetcode 494. Target Sum
- leetcode-494. Target Sum
- leetcode:494. Target Sum
- (LeetCode) 494. Target Sum
- LeetCode 494. Target Sum
- leetcode 494. Target Sum
- LeetCode 494. Target Sum
- LeetCode 494. Target Sum
- LeetCode 494. Target Sum
- [leetcode] 494. Target Sum
- [LeetCode] 494. Target Sum
- LeetCode笔记:494. Target Sum
- LeetCode题目:494. Target Sum
- JavaBean编程学习--使用JavaBean提高JSP的代码重用性
- codevs1060 搞笑世界杯(dp)
- vmware workstation11 虚拟机连接网络配置
- python制作一个简单网络爬虫
- 面试题23从上往下打印二叉树
- (LeetCode) 494. Target Sum
- JQuery,Validation,Bootstrap
- 自定义Git及Git简单的命令总结
- 进程学习1--atexit
- 关于EL表达式的复习
- io 哈哈哈估计只有我自己能看懂
- hibernate学习笔记01--基本API
- [Codeforces][后缀自动机]Helvetic Coding Contest 2017 . I Fake News (hard)
- 玲珑oj 1125