Solution
-
Store sums and # ways up to
nums[i-1]into a dictionarydic. -
For
nums[i], create a new dictionary. -
For each sum in
dicup tonums[i-1],sum+kandsum-kcan be created indic[sum]MORE ways.This is because
sum1-kcan be equalsum2+k.
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
dic = collections.Counter({0:1})
for num in nums:
new_dic = collections.Counter()
for k in dic:
if k in dic:
new_dic[k + num] += dic[k]
new_dic[k - num] += dic[k]
dic = new_dic
return dic[S]