Changchun Master Li

leetcode 494 Target Sum

2017-08-12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
SUM = 0
for num in nums:
SUM += num

if SUM < S or (SUM + S) %2 == 1:
return 0

SUM = (SUM + S) /2
DP = [0] *(SUM + 1)
DP[0] = 1

for num in nums:
for i in reversed(range(len(DP))):
if i - num >=0:
DP[i] = DP[i] + DP[i - num]
else:
break
return DP[-1]

reference
similar problem

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章