[leetcode]494.C++实现 目标和(Target Sum)

(一)题目描述

[leetcode]494.C++实现 目标和(Target Sum)_第1张图片

[leetcode]494.C++实现 目标和(Target Sum)_第2张图片

(二)思想方法

  • 于是我们可以知道:target = sum(P) - sum(N);
  • 那么sum(P) + sum(N) + sum(P) - sum(N) = sum(S) + target = 2sum(P);
  • 那么sum(P) = [target + sum(S)] / 2;

 

(三)代码实现

class Solution {
public:
    int findTargetSumWays(vector& nums, int S) {
       
        int sum = 0;
        for (int i = 0; i < (int)nums.size(); i++) {
            sum += nums[i];
        }
        if (sum < S || (sum + S) % 2 != 0) {
            return 0;
        }
        int target = (S + sum) / 2;
        int dp[target + 1];
        for (int i = 0 ; i < target+1; i++) {
            dp[i] = 0;
        }
        dp[0] = 1;
        for (int i = 0; i < (int)nums.size(); i++) {
            for (int j = target; j >= nums[i]; j--) {
                dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }
};
   

 

你可能感兴趣的:(算法,leetcode)