leetcode 494
来源:互联网 发布:linux vim 强制保存 编辑:程序博客网 时间:2024/05/23 00:01
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.
Subscribe to see which companies asked this question.
坑: +0 -0算两次!
1:递归 超时了嘤嘤嘤
class Solution {
public:
int findTargetSumWays(vector<int> nums, int S) {
int size = nums.size();
if (size == 1)
{
if(S == nums[0] || S == -1* nums[0])
{
if(nums[0] == 0)
return 2;
else
{
//cout<<size << " " << nums[size-1]<<" "<<S << endl;
return 1;
}
}
else
return 0;
}
int a = nums[size -1];
//cout<<size << " " << nums[size-1]<<" "<<S << endl;
nums.pop_back();
return findTargetSumWays(nums, S - a) + findTargetSumWays(nums, S + a);
}
};
2:考虑到存中间变量,网上解法:
The sum of elements in the given array will not exceed 1000.
所以[2001]数组就可以表示一层,下表为和,值为多少种
class Solution {
public:
int findTargetSumWays(vector<int> nums, int S) {
if (S>1000 || S < -1000)
return 0;
int* rel = new int [2001];
int* pre = new int [2001];
memset(pre, 0, sizeof(rel));
memset(rel, 0, sizeof(rel));
//rel[1000] = 1;
pre[nums[0] + 1000] += 1;
pre[-1 * nums[0] + 1000] += 1;
for(int i = 1; i < nums.size() ; i ++)
{
for(int j = 0 ; j < 2001; j ++)
{
if(pre[j] != 0)
{
rel[j + nums[i]] += pre[j] ;
rel[j - nums[i]] += pre[j] ;
}
}
for (int k = 0; k < 2001; k ++)
{
pre[k] = rel[k];
rel[k] = 0;
//cout << k<<" "<<rel[k]<<endl;
}
//cout<<"--------"<<endl;
}
return pre[S + 1000];
}
};
- leetcode 494
- leetcode 494
- leetcode 494
- leetcode[494]:Target Sum
- leetCode练习(494)
- LeetCode 494:Target Sum
- leetcode 494 Target sum
- leetcode(494). Target Sum
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- source inisight无法跳转
- BIEE 11g catalog自动复制
- 非SSL协议 CAS服务端部署及客户端配置
- Oracle基本语法之DML(二)
- 散列函数与层级结构数据
- leetcode 494
- 服务端改造(登录页及登录方式的自定义)
- hdu 1003 Max Sum (dp)
- 二进制中1的个数
- 2017年中国国际信息通信展览会
- RecyclerView头布局添加
- 卷积神经网络入门一种全卷积神经网络(LeNet),从左至右依次为卷积→子采样→卷积→子采样→全连接→全连接→高斯连接测试 最后,为了检验 CNN 能否工作,我们准备不同的另一组图片与标记集(不能在训练
- 二叉树的前序,后序,中序,层次遍历
- Java 在传输JSON数据时,数据被最后所赋值的内容覆盖