dp问题
转移方程:sumcount(nums,n,targetsum)=sumcount(nums,n-1, targetsum-nums[n])+sumcount(nums,n-1,targetsum)
| include当前nums[i] |exclude 当前nums[i]
boundary:
sumcount(nums,0,targetsum) =0 当include 0个nums里面元素到subset时,无论targetsum为任何数。有0种组合
sumcount(nums,i, 0) =1 当include/exclude任何个nums里面元素到subset时,都可以得到targetsum为0。
def sumcount(par,nums):
dp=[]# crease array to store the sumcounts
target=par[1]
for i in range(len(nums)+1):
row_list=[]
for t in range(target+1):
if t==0:
row_list.append(1)# boundary sumcount(nums,i, 0) =1
else:
row_list.append(0)#boundary sumcount(nums,0,targetsum) =0
dp.append(row_list)
for i in range(1,len(nums)+1):
for t in range(1,target+1):
if t-nums[i-1]<0:
last_count=0
else:
last_count=dp[i-1][t-nums[i-1]]
dp[i][t]=last_count+dp[i-1][t]#转移方程
return(dp[-1][-1])
par=[int(i) for i in input().strip("[]").split(" ")]
nums=[int(i) for i in input().strip("[]").split(" ")]