Target Sum(01背包dp,dfs with memo)

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols+and-. For each integer, you should choose one from+and-as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input:
 nums is [1, 1, 1, 1, 1], S is 3. 

Output:
 5

Explanation:


-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3

分析

求方案总数的01背包问题:https://www.kancloud.cn/kancloud/pack/70133

f[i][v]=sum{f[i-1][v],f[i][v-c[i]]}

初始条件f[0][0]=1。

其实就是01背包问题。取不取dp[i][j+/-value] 这里因为j-value会有负数,所以平移 0<=j<=2sum

初始化dp[0][sum]= 1 其实这里sum代表了起始0点,然后往左0和往右2sum。0数 = 0的确是一种

这里算出来所有的sum,然后结果取到S即可。记住这里起始点是sum, 所以是sum+S

这里背包容量V= 2*sum,所以target是sum+S

dfs with memo

记住判断map的key是否存在 是key in dict,不是dict[key]或者Get(key)

这是01背包方案数: f[i][v]=sum{f[i-1][v],f[i][v-c[i]]} 初始化f[0][0]=1 联想答案都是前面相加,总得有个初始点给出数值。

这里难点是target,做法1的target 是把array分成p,q两段,所以相加是all,q不取p是取,所以相减是S

方案数最后的target/背包大小都要/2?

网上做法1

网上做法2

Last updated

Was this helpful?