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.c++

Find out how many ways to assign symbols to make sum of integers equal to target S.git

Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:code

-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 = 3element

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.get

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) / 2it

解題思想:動態規劃。dp[j] = dp[j] + dp[j - n]io

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];
    }
};
相關文章
相關標籤/搜索