Target Sum

来源:互联网 发布:内蒙广电网络登录入口 编辑:程序博客网 时间:2024/05/16 01:09

1.问题描述
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.

2 求解思路
使用动态规划dp来求解该问题.令A(i,s)表示前i个点组合成和s的组合方式.则存在一下动态规划的转移方程.A(i,s)=A(i-1,s-ai)+A(i-1,s+ai).根据此转移方程.设计两个数组分别存放一次迭代前后迭代后的值. 由于不知道和的范围,因此将所有值取正值,求和得到正的最大值,
3代码

class Solution{    public:        int findTargetSumWays(vector<int>& nums,int s){            int sum=0;            for(int i=0;i<nums.size();i++){                sum+=nums[i];            }            vector<int> v1(2*sum+1,0);            v1[sum]=1;            for(int i=0;i<nums.size();i++){                vector<int> v2(2*sum+1,0);                for(int j=0;j<v1.size();j++){                    if(v1[j]!=0){                        v2[j-nums[i]]+=v1[j];                        v2[j+nums[i]]+=v1[j];                    }                }                v1=v2;            }            return v1[sum+s];        }};
原创粉丝点击