Combination Sum II

Recursion FAQs (Medium) Medium
  • This problem can be framed as a subset sum problem, which has a wide range of applications in the software industry, particularly in financial technology (fintech) and inventory management systems
  • For example, in a stock trading application, an algorithm might need to find combinations of stocks that add up to a user's specified budget
  • Similarly, in inventory management, it could assist in finding combinations of items to fulfill a certain order, given constraints such as weight or cost

Given collection of candidate numbers (candidates) and a integer target.Find all unique combinations in candidates where the sum is equal to the target.There can only be one usage of each number in the candidates combination and return the answer in sorted order.


e.g : The combination [1, 1, 2] and [1, 2, 1] are not unique.

Examples:

Input : candidates = [2, 1, 2, 7, 6, 1, 5] , target = 8

Output : [ [1, 1, 6] , [1, 2, 5] , [1, 7] , [2, 6] ]

Explanation : The combinations sum up to target are

1 + 1 + 6 => 8.

1 + 2 + 5 => 8.

1 + 7 => 8.

2 + 6 => 8.

Input : candidates = [2, 5, 2, 1, 2] , target = 5

Output : [ [1, 2, 2] , [5] ]

Explanation : The combinations sum up to target are

1 + 2 + 2 => 5.

5 => 5.

Input : candidates = [2, 1, 2] , target = 5

Constraints

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Hints

  • Use recursion to explore all possible combinations. Stop when the target becomes zero (a valid combination is found) or when the target becomes negative (discard the branch).
  • "Sort the input array candidates to handle duplicates easily. Skip duplicates during recursion: If candidates[i]==candidates[i-1] and i>start, skip the current element."

Company Tags

Cerner Broadcom American Express Epic Systems Teladoc Health eBay NVIDIA Bain & Company Uber Western Digital Snowflake DoorDash Morgan Stanley Stripe Lyft HashiCorp Red Hat Instacart Splunk Chewy IBM Philips Healthcare Roblox MongoDB JPMorgan Chase Google Microsoft Amazon Meta Apple Netflix Adobe