Header Ad

Leetcode Target Sum problem solution

In this Leetcode Target Sum problem solution You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".

Return the number of different expressions that you can build, which evaluates to target.

Leetcode Target Sum problem solution


Problem solution in Python.

class Solution:
    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        zero_cnt = nums.count(0)
        nums = list(filter(lambda x:x!=0, nums))
        if not nums: return 2**zero_cnt
        dic = {nums[0]:1, -nums[0]:1}
        
        for n in nums[1:]:
            new_dic = dict()
            for k in dic.keys():
                for sign in [1,-1]:
                    d = n * sign
                    if k+d not in new_dic:
                        new_dic[k+d] = dic[k]
                    else:
                        new_dic[k+d] += dic[k]
            dic = new_dic
        res = dic[S] if S in dic else 0
        res = res if zero_cnt == 0 else res * 2**zero_cnt
        return res

Problem solution in Java.

public class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        return findWays(nums, 0, S);
    }
    
    public int findWays(int[] nums, int start, int S) {
        int n = nums.length;
        if (start >= nums.length) {
            return S == 0 ? 1 : 0;
        }
        return findWays(nums, start + 1, S - nums[start]) + findWays(nums, start + 1, S + nums[start]);
    }

}


Problem solution in C++.

class Solution {
public:
    int dp[32 * 2001] = {[0 ... 32 * 2000 - 1] = -1};
    int findTargetSumWays(vector<int>& nums, int t, int pos=0) {
        if (pos == nums.size()) return !t;
        int i = pos * 2001 + t + 1000;
        if (dp[i] >= 0) return dp[i];
        return dp[i] = findTargetSumWays(nums, nums[pos] + t, pos + 1) +
            findTargetSumWays(nums, -nums[pos] + t, pos + 1);
    }
};

Post a Comment

0 Comments