LeetCode 494: Target Sum

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 494: Target Sum相关的知识,希望对你有一定的参考价值。

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if (nums.length == 0) {
            return 0;
        }
        
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        
        if (S > sum || S < -sum) {
            return 0;
        }
        
        int[] dp = new int[2 * sum + 1];
        dp[sum] = 1;
        for (int i = 0; i < nums.length; i++) {
            int[] next = new int[2 * sum + 1];
            for (int j = 0; j < 2 * sum + 1; j++) {
                if (j - nums[i] >= 0 && j + nums[i] < 2 * sum + 1) {
                    next[j - nums[i]] += dp[j];
                    next[j + nums[i]] += dp[j];
                }
                
            }
            dp = next;
        }
        
        return dp[sum + S];
    }
    
}

 

以上是关于LeetCode 494: Target Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 494: Target Sum

LeetCode 494. Target Sum

[leetcode-494-Target Sum]

LeetCode 494. Target Sum

leetcode494 - Target Sum - medium

LeetCode 494. Target Sum