1、题目描述:
2、题解:
转化为01背包,nums数组的元素等价于物品的数量,和nums和的2倍为背包的容量。dp[ i ][ j ]定义为从数组nums中 0 - i 的元素进行加减可以得到 j 的方法数量。
dp[ i ][ j ] = dp[ i - 1 ][ j - nums[ i ] ] + dp[ i - 1 ][ j + nums[ i ] ],物品不是选与不选,而是+或者-
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
#动态规划,01背包
n = len(nums)
sumation = 0
for num in nums:
sumation += num
if abs(sumation) < abs(S): return 0
length = (2 * sumation) + 1
dp = [[0 for _ in range(length)] for _ in range(n)]
dp[0][sumation + nums[0]] = 1
dp[0][sumation - nums[0]] += 1
for i in range(1, n):
for j in range(length):
l = dp[i - 1][j - nums[i]] if 0 <= j - nums[i] < length else 0
r = dp[i - 1][j + nums[i]] if 0 <= j + nums[i] < length else 0
dp[i][j] = l + r
return dp[n - 1][sumation + S]