smj007

Target Sum (and find all expressions)

Aug 11th, 2025 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.50 KB | None | 0 0
  1. from typing import List
  2.  
  3. class Solution:
  4.     def findTargetSumWays(self, nums: List[int], target: int) -> int:
  5.         # Calculate the total sum of all numbers in nums
  6.         # This helps us define the range of possible sums (-total_sum to +total_sum)
  7.         total_sum = sum(nums)
  8.  
  9.         # Initialize a memoization table with size:
  10.         # rows -> number of elements in nums
  11.         # cols -> range of possible sums from -total_sum to +total_sum
  12.         # Using -inf as a marker for "not yet computed"
  13.         memo = [[-float("inf")] * (2 * total_sum + 1) for _ in range(len(nums))]
  14.  
  15.         def dfs(index, current_sum):
  16.             """
  17.            Recursive DFS function to explore all combinations of '+' and '-'
  18.            for each number to try and reach the target sum.
  19.  
  20.            Args:
  21.                index: Current index in nums we are processing
  22.                current_sum: The sum we have accumulated so far
  23.  
  24.            Returns:
  25.                Number of ways to assign + or - to nums[index:] to reach the target
  26.            """
  27.  
  28.             # Base case: If we've processed all numbers
  29.             if index == len(nums):
  30.                 # If the accumulated sum equals the target, it's a valid way
  31.                 return 1 if current_sum == target else 0
  32.  
  33.             # If this state has been computed before, return it from memo
  34.             if memo[index][current_sum + total_sum] != -float("inf"):
  35.                 return memo[index][current_sum + total_sum]
  36.  
  37.             # Choice 1: Add the current number
  38.             add = dfs(index + 1, current_sum + nums[index])
  39.  
  40.             # Choice 2: Subtract the current number
  41.             subtract = dfs(index + 1, current_sum - nums[index])
  42.  
  43.             # Store the total ways in memo to avoid recomputation
  44.             memo[index][current_sum + total_sum] = add + subtract
  45.  
  46.             # Return the total ways for this state
  47.             return add + subtract
  48.  
  49.         # Start DFS from index 0 and initial sum 0
  50.         return dfs(0, 0)
  51.  
  52.  
  53. from typing import List, Dict, Tuple
  54.  
  55. class Solution:
  56.     def findTargetSumComb(self, nums: List[int], target: int) -> List[str]:
  57.         """
  58.        Return all +/− assignments that evaluate to `target`.
  59.        Output format: strings like "+1-2+3" (one sign per number, in order).
  60.        """
  61.         memo: Dict[Tuple[int, int], List[List[str]]] = {}
  62.  
  63.         def dfs(index: int, current_sum: int) -> List[List[str]]:
  64.             # If we've placed signs for all numbers, check if we hit target
  65.             if index == len(nums):
  66.                 return [[]] if current_sum == target else []
  67.  
  68.             key = (index, current_sum)
  69.             if key in memo:
  70.                 return memo[key]
  71.  
  72.             res: List[List[str]] = []
  73.  
  74.             # Option 1: place '+'
  75.             for tail in dfs(index + 1, current_sum + nums[index]):
  76.                 res.append([f"+{nums[index]}"] + tail)
  77.  
  78.             # Option 2: place '−'
  79.             for tail in dfs(index + 1, current_sum - nums[index]):
  80.                 res.append([f"-{nums[index]}"] + tail)
  81.  
  82.             memo[key] = res
  83.             return res
  84.  
  85.         parts_lists = dfs(0, 0)
  86.         # Join each list of parts into an expression string
  87.         return ["".join(parts) for parts in parts_lists]
  88.  
  89.     def findTargetSumWays(self, nums: List[int], target: int) -> int:
  90.         """
  91.        (Optional) Keep the original count API: just return the number of combinations.
  92.        """
  93.         return len(self.findTargetSumComb(nums, target))
  94.  
Advertisement
Add Comment
Please, Sign In to add comment