Leetcode 494 Solution

This article provides solution to leetcode question 494 (target-sum)

https://leetcode.com/problems/target-sum

Solution

class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        n = len(nums)

        s = sum(nums)

        if s < target or (s - target) % 2 != 0:
            return 0

        goal = (s - target) // 2

        dp = [0 for _ in range(goal + 1)]
        dp[0] = 1

        for num in nums:
            for i in range(goal, num - 1, -1):
                dp[i] += dp[i - num]

        return dp[goal]