Target Sum

来源:互联网 发布:淘宝助手是什么 编辑:程序博客网 时间:2024/06/05 02:28

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:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.

  1. Your output answer is guaranteed to be fitted in a 32-bit integer.
题目意思为寻找给定数组的一个全部为正的子集A,以及该子集的补集B,满足子集A中所有元素的和减去子集B中所有元素的和等于target的值。
我们首先建立一个函数sum(vector<int>& nums),计算某一数组元素的和。
将问题进行转换,根据我们的分析
sum(A)-sum(B)=target
sum(A)+sum(B)+sum(A)-sum(B)=target+sum(A)+sum(B)
2*sum(A)=target+sum(nums)
所以我们的任务是寻找这样一个数组的子集,该子集满足2*sum(A)=target+sum(nums)

函数部分设计如下:
int findTargetSumWays(vector<int>& nums, int s) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        return sum < s || (s + sum) & 1 ? 0 : subsetSum(nums, (s + sum) >> 1); 

 }   

int subsetSum(vector<int>& nums, int s) {
int dp[s + 1] = { 0 };
        dp[0] = 1;
        for (int n : nums)
            for (int i = s; i >= n; i--)
                dp[i] += dp[i - n];
        return dp[s];

 }

测试正确

原创粉丝点击