Combination Sum

Recursion FAQs (Medium) Medium
  • This problem is a classic demonstration of combinatorial search and dynamic programming, and it's often encountered in real-world scenarios, especially in e-commerce and budgeting-oriented applications
  • For example, given a budget, we might want to find all combinations of products (represented by their prices) that would total up to the budget
  • The problem also relates to other cases such as coin change problems, which are popular in coding interviews, and are used behind the scenes in ATM and cash transactions, to provide the fewest possible number of coins or bills

Provided with a goal integer target and an array of unique integer candidates, provide a list of all possible combinations of candidates in which the selected numbers add up to the target. The combinations can be returned in any order.


A candidate may be selected from the pool an infinite number of times. There are two distinct combinations if the frequency if at least one of the selected figures differs.


The test cases are created so that, for the given input, there are fewer than 150 possible combinations that add up to the target.

If there is no possible subsequences then return empty vector.

Examples:

Input : candidates = [2, 3, 5, 4] , target = 7

Output : [ [2, 2, 3] , [3, 4] , [5, 2] ]

Explanation :

2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.

5 and 2 are candidates, and 5 + 2 = 7.

3 and 4 are candidates, and 3 + 4 = 7.

There are total three combinations.

Input : candidates = [2], target = 1

Output : []

Explanation : There is no way we can choose the candidates to sum up to target.

Input : candidates = [1], target = 1

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

Hints

  • Use recursion to explore all combinations of numbers: Include the current number and subtract it from the target. Skip the current number and move to the next candidate.
  • Start each recursive call with the current index to avoid revisiting previous elements and prevent duplicate combinations.

Company Tags

JPMorgan Chase Mastercard Cerner Broadcom PayPal Shopify Snowflake Walmart Intel Boston Consulting Group Stripe Dropbox Philips Healthcare Morgan Stanley KPMG Byju's Unity Technologies Databricks Visa Pinterest Robinhood Ubisoft Wayfair Optum Goldman Sachs Google Microsoft Amazon Meta Apple Netflix Adobe