#494

Target Sum

Medium
ArrayDynamic ProgrammingBacktrackingDynamic ProgrammingBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n)
O(n * sum(nums))
Space
O(n)
O(sum(nums))
💡

Intuition

Time O(n * sum(nums))Space O(sum(nums))

The optimal approach uses dynamic programming to count the number of ways to achieve the target sum. Instead of exploring all combinations, we build a table that keeps track of the number of ways to reach each possible sum using the numbers provided.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total sum of nums and determine the required positive sum needed to reach the target.
  2. 2Step 2: Use dynamic programming to find the number of ways to achieve this positive sum using the numbers in nums.
  3. 3Step 3: Return the count of ways to achieve the target.
solution.py11 lines
1def findTargetSumWays(nums, target):
2    total_sum = sum(nums)
3    if total_sum < target or (total_sum + target) % 2 != 0:
4        return 0
5    positive_sum = (total_sum + target) // 2
6    dp = [0] * (positive_sum + 1)
7    dp[0] = 1
8    for num in nums:
9        for j in range(positive_sum, num - 1, -1):
10            dp[j] += dp[j - num]
11    return dp[positive_sum]

Complexity note: The time complexity is O(n * sum(nums)) because we iterate through each number and update our dp array for each possible sum. The space complexity is O(sum(nums)) due to the dp array storing counts for each possible sum.

  • 1The problem can be transformed into a subset sum problem.
  • 2Dynamic programming is effective for counting combinations rather than generating them.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.