class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
if (target+sum(nums))%2 != 0:
return 0
elif target<0 and (-sum(nums)) > target:
return 0
left = (target+sum(nums))//2
#dp[j]装满容量j的背包,有几种方法
dp = [0] * (left+1)
dp[0] = 1
for i in range(len(nums)):
for j in range(left,nums[i]-1,-1):
#如果有选择nums[i],那么就有dp[j-num[i]]种方法凑成j
dp[j] += dp[j-nums[i]]
return dp[left]
494. 目标和
最新推荐文章于 2024-08-17 15:37:21 发布