494. Target Sum
来源:互联网 发布:全天时时彩计划数据 编辑:程序博客网 时间:2024/05/29 17:50
- Total Accepted: 16739
- Total Submissions: 38242
- Difficulty: Medium
- Contributors: kevin.xinzhao@gmail.com
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.
解题思路:
对于一个数组nums,在增加加号或者减号之后他的和值范围是 [-sum(nums), sum(nums)]。对于nums中的每一个数,都有加和减两种选择。得到的这两个结果再加或者减第二个数,又有4个结果。用dp[i + sum(nums)] 来记录每次操作之后使得和为i的方法数,经过一轮操作后dp[S+sum(nums)] 就是答案。
代码:
class Solution {public: int findTargetSumWays(vector<int>& nums, int S) { int sum = 0; for(int i = 0; i < nums.size(); i++) sum += nums[i]; if(S > sum || S < -sum || (S+sum)%2 != 0) return 0; int dp[2001] = {0}; dp[sum] = 1; for(int i = 0; i < nums.size(); i++){ int next[2001] = {0}; for(int j = 0; j < 2 * sum + 1; j++){ if(dp[j] != 0){ next[j - nums[i]] += dp[j]; next[j + nums[i]] += dp[j]; } } for(int j = 0; j < 2 * sum + 1; j++) dp[j] = next[j]; } return dp[sum + S]; }};
0 0
- 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
- Android翻书翻页(支持硬翻软翻)
- MS SQL varchar索引与查询
- java 成长之路
- 记忆网络RNN、LSTM与GRU
- Android-网络通信框架Volley使用详解
- 494. Target Sum
- 静态分析工具
- 正确评估SQL数据库性能,你必须知道的原理和方法!
- 给自己看的Redis
- C#调用python
- 基于Spring的Github第三方登录--通用化的第三方登陆实现
- android textView、语音播报
- Expected one result (or null) to be returned by selectOne(), but found
- selenium2java写一个强制刷新页面的方法(ctrl+F5)