Easily understood solution in 8 lines


  • 8

    I used python, but it's really easy to understand.
    To make it clear for everyone, find following the syntax for get() method of dictionary(hase map)

    dict.get(key, default)
    

    The method get() returns a value for the given key. If key is not available then returns default value.

    def findTargetSumWays(self, nums, S):
        count = {0: 1}
        for x in nums:
          count2 = {}
          for tmpSum in count:
            count2[tmpSum + x] = count2.get(tmpSum + x, 0) + count[tmpSum]
            count2[tmpSum - x] = count2.get(tmpSum - x, 0) + count[tmpSum]
          count = count2
        return count.get(S, 0)
    

  • 5
    S

    Great code!

    One small change: defaultdict is pretty useful.

    def findTargetSumWays(self, nums, S):
        count = defaultdict(int)
        count[0] = 1
        for x in nums:
            step = defaultdict(int)
            for y in count:
                step[y + x] += count[y]
                step[y - x] += count[y]
            count = step
    
        return count[S]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.