494. Target Sum
来源:互联网 发布:郭德纲才学 知乎 编辑:程序博客网 时间:2024/06/06 08:36
题目
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.
思路
动态规划思想。关系式为dp[i][sum+nums[i]]=dp[i][sum+nums[i]]+dp[i−1][sum]. dp为总和为S的数量
代码
class Solution {public: int findTargetSumWays(vector<int>& nums, int S) { vector<vector<int>>dp(nums.size(),vector<int>(2001,0)); dp[0][nums[0] + 1000] = 1; dp[0][-nums[0] + 1000] += 1; for (int i = 1; i < nums.size(); i++) { for (int sum = -1000; sum <= 1000; sum++) { if (dp[i - 1][sum + 1000] > 0) { dp[i][sum + nums[i] + 1000] += dp[i - 1][sum + 1000]; dp[i][sum - nums[i] + 1000] += dp[i - 1][sum + 1000]; } } } return S > 1000 ? 0 : dp[nums.size() - 1][S + 1000]; }};
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- 494. Target Sum
- [leetcode]494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum -Medium
- 494. Target Sum
- Leetcode-494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum
- leetcode-494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- P1025 小飞侠的游园方案
- mabaties基础篇
- 关于linux的学习分享
- 动态规划算法
- java对象池commons-pool-1.6详解(三)
- 494. Target Sum
- Android 6开发秘籍 第5版.pdf 免费下载
- Makefile:xxx: recipe for target xxx failed +【顺带搞懂了】如何忽略makefile执行过程中的某些命令的错误而得以继续运行
- Beginning Ractive.js-Apress(2017).pdf 英文原版 免费下载
- java包装器类拆装箱特别注意的问题
- 红黑树
- 降维和度量学习
- Git指令整理
- Build Android-Based Smart Applications (2018).pdf 英文原版 免费下载