Leetcode——Target Sum

Question

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.

Solution

这道题相当于找一个子集求和减去剩下的集合求和等于目标值。P表示positive, N表示Negitive
// sum(P) - sum(N) = S
// sum(P) + sum(N) + sum(P) - sum(N) = S + sum(All)
// 2sum(P) = sum(All) + S
// sum(P) = (sum(All) + S) / 2

解题思想:动态规划。dp[j] = dp[j] + dp[j - n]

Code

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        // sum(P) - sum(N) = S
        // sum(P) + sum(N) + sum(P) - sum(N) = S + sum(All)
        // 2sum(P) = sum(All) + S
        // sum(P) = (sum(All) + S) / 2
        int sum = 0;
        for (int n : nums)
            sum += n;
        if ((sum + S) & 1 == 1 || sum < S)
            return 0;
        sum = (sum + S) / 2;
        return subsetsum(nums, sum);
    }
    int subsetsum(vector<int>& nums, int sum) {
        int dp[sum + 1] = {0};
        dp[0] = 1;
        for (int n : nums) {
            for (int j = sum; j >= n; j--)
                dp[j] += dp[j - n];
        }
        return dp[sum];
    }
};

猜你喜欢

转载自www.cnblogs.com/zhonghuasong/p/9369882.html
今日推荐