题目
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.
示例
**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.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
题解
先上代码:
class Solution:
def findTargetSumWays(self, nums, S):
summary = sum(nums)
if S > summary or S < -summary:
return 0
dp = [0]*(2*summary+1)
dp[summary-nums[0]] += 1
dp[summary+nums[0]] += 1
for i in range(1, len(nums)):
tmp = [0] * (2*summary+1)
for j in range(2*summary+1):
if dp[j] != 0:
tmp[j + nums[i]] += dp[j]
tmp[j - nums[i]] += dp[j]
dp = list(tmp)
return dp[S+summary]
说下思路吧:
这道题是动态规划,如果暴力去算的话时间复杂度是
2
n
2^{n}
2n,以动态规划的思想来说呢就是以空间换时间,令dp[i]
存放的是前k
个num
进行运算能得到结果i
的方案数,那么显然有dp[i+num[k]] = dp[i]
和dp[i-num[k]] = dp[i]
,但里面有一个小坑就是得用一个新数组来保存本次更新,而不能直接在原来的数组上操作,因为会造成本次从0变成1的在右边的数当本次遍历过来的时候又做了一次,而实际上这个数字应该下一次才进行运算。另外有个小坑是当第一个数字是0的时候,初始化那里dp[summary-nums[0]] += 1
和 dp[summary+nums[0]] += 1
应当是+=
而不是=
这会造成漏算。