思想:动态规划,提示一点,虽然时间复杂度是(O(2^n)),但是实际上在动态规划中,有些步数会得到优化
import collections
class Solution:
def findTargetSumWays(self, nums: [int], S: int) -> int:
dp = {0: 1}
for num in nums:
dp2 = dict(dp)
dp = collections.defaultdict(int)
for k, v in dp2.items():
dp[k + num] += v
dp[k - num] += v
return dp[S]