Program to find number of ways we can arrange symbols to get target in Python?

Suppose we have a list of non-negative numbers called nums and also have an integer target. We have to find the number of ways to arrange + and - signs in front of nums such that the expression equals the target.

So, if the input is like nums = [2, 3, 3, 3, 2] target = 9, then the output will be 2, as we can have −2 + 3 + 3 + 3 + 2 and 2 + 3 + 3 + 3 − 2.

Algorithm Approach

This problem can be transformed into a subset sum problem. If we assign positive signs to some numbers and negative signs to others, we can find the target sum by:

  • s := sum of all numbers in nums

  • if (s + target) mod 2 is not same as 0 or target > s, then return 0

  • W := quotient of (s + target) / 2

  • Use dynamic programming to count ways to achieve sum W

Example

Here's the complete implementation using dynamic programming ?

class Solution:
    def solve(self, nums, target):
        s = sum(nums)
        if (s + target) % 2 != 0 or target > s:
            return 0
        W = (s + target) // 2
        dp1 = [0] * (W + 1)
        dp1[0] = 1
        dp2 = [0] * (W + 1)
        for i in range(len(nums)):
            for j in range(W + 1):
                if j >= nums[i]:
                    dp2[j] += dp1[j - nums[i]]
            for j in range(W + 1):
                dp1[j] += dp2[j]
                dp2[j] = 0
        return dp1[-1]

ob = Solution()
nums = [2, 3, 3, 3, 2]
target = 9
print(ob.solve(nums, target))
2

How It Works

The algorithm transforms the problem into finding subsets that sum to W = (s + target) / 2. This works because if we have a subset with sum W that gets positive signs, the remaining elements get negative signs, resulting in the target sum.

Step-by-Step Breakdown

def find_target_sum_ways(nums, target):
    s = sum(nums)
    print(f"Total sum: {s}")
    
    # Check if solution is possible
    if (s + target) % 2 != 0 or target > s:
        return 0
    
    W = (s + target) // 2
    print(f"Target subset sum: {W}")
    
    # DP array to count ways
    dp = [0] * (W + 1)
    dp[0] = 1  # One way to make sum 0 (empty subset)
    
    for num in nums:
        for j in range(W, num - 1, -1):
            dp[j] += dp[j - num]
    
    return dp[W]

nums = [2, 3, 3, 3, 2]
target = 9
result = find_target_sum_ways(nums, target)
print(f"Number of ways: {result}")
Total sum: 13
Target subset sum: 11
Number of ways: 2

Conclusion

This problem uses dynamic programming to count subset combinations that achieve a specific sum. The key insight is transforming the target sum problem into a subset sum counting problem, making it solvable with standard DP techniques.

Updated on: 2026-03-25T12:05:41+05:30

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements