MediumBacktrackingRecursionArray

Combination Sum

LeetCode
1 approach, code in all languages

You are given a list of distinct positive integers called candidates and a positive whole number target. Find every unique group of numbers drawn from candidates whose elements add up exactly to target. A single candidate value may be reused as many times as you like within one group.

Two groups are considered the same if they contain the identical multiset of numbers regardless of order, so each distinct combination should be reported only once. Return all the combinations in any order.

Example 1

Input: candidates = [2, 3, 6, 7], target = 7

Output: [[2, 2, 3], [7]]

Two plus two plus three equals seven, and seven by itself also reaches the target.

Example 2

Input: candidates = [2, 3, 5], target = 8

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

Each listed group sums to eight and no group repeats another as a multiset.

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All values in candidates are distinct
  • 1 <= target <= 500
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now