Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.

Example 1:
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.

My code:

class Solution(object):
    #Same idea, python can only pass some
    def findTargetSumWays1(self, nums, S):
        """
        :type nums: List[int]
        :type S: int
        :rtype: int
        """
        if len(nums)==0 and S==0:
            return 1
        elif len(nums)==0:
            return 0
        count1=self.findTargetSumWays(nums[1:], S-nums[0])
        count2=self.findTargetSumWays(nums[1:], S+nums[0])
        return count1+count2
    class Solution(object):
    #Same idea, python can only pass some
    def findTargetSumWays1(self, nums, S):
        """
        :type nums: List[int]
        :type S: int
        :rtype: int
        """
        if len(nums)==0 and S==0:
            return 1
        elif len(nums)==0:
            return 0
        count1=self.findTargetSumWays(nums[1:], S-nums[0])
        count2=self.findTargetSumWays(nums[1:], S+nums[0])
        return count1+count2
    def findTargetSumWays(self, nums, S):
        def recur(i,s):
            if i == n: return 1 if s == 0 else 0
            if s<-sums[i] or s > sums[i]: return 0
            if (i,s) not in memo:
                memo[(i,s)] = recur(i+1,s-nums[i]) + recur(i+1,s+nums[i])    
            return memo[(i,s)]
        n = len(nums);memo = {}
        sums = [nums[-1]] * n
        for i in range(n-2,-1,-1):
            sums[i] = nums[i] + sums[i+1]
        return recur(0,S)
        
        
        
        
        
        

Solution: https://leetcode.com/problems/target-sum/submissions/