0

[Structy] Follow ups on "Sum Possible" question

Profile picture
Senior Software Engineer at Taro Communitya month ago

I was looking to try out this one -
https://www.jointaro.com/course/crash-course-data-structures-and-algorithms-concepts/sum-possible-walkthrough/

I've found similar versions of this problem on Leetcode. eg. 2 sum, 3 sum find all the different ways how a target some can be reached etc.

  1. Where is this problem on LeetCode?
  2. If we wanted the different ways a target could be reached, how do we do that?
17
1

Discussion

(1 comment)
  • 0
    Profile picture
    Tech Lead @ Robinhood, Meta, Course Hero
    a month ago

    Where is this problem on LeetCode?

    I don't think this problem exists there. This is the closest one I think (which is harder as you need to return the list): https://leetcode.com/problems/combination-sum/description/

    If we wanted the different ways a target could be reached, how do we do that?

    That's pretty much the Combination Sum problem I linked above (it even has the stipulation that you can reuse numbers). Here's a Python solution:

    class Solution:
        def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
            # This list will store all unique combinations that sum up to the target
            result = []
    
            # Helper function for backtracking
            def backtrack(start_index, current_combination, current_sum):
                # If the current sum matches the target, add the combination to the result
                if current_sum == target:
                    result.append(list(current_combination))  # Make a copy before appending
                    return
                
                # If the current sum exceeds the target, stop exploring this path
                if current_sum > target:
                    return
    
                # Iterate through candidates starting from the current index
                for i in range(start_index, len(candidates)):
                    # Add the current candidate to the combination
                    current_combination.append(candidates[i])
    
                    # Recursively call backtrack with the same index (allowing reuse of the same number)
                    backtrack(i, current_combination, current_sum + candidates[i])
    
                    # Remove the last added number to backtrack and explore other possibilities
                    current_combination.pop()
    
            # Start the backtracking process from index 0, with an empty combination and a sum of 0
            backtrack(0, [], 0)
    
            # Return the list of all unique valid combinations
            return result