Uber · Question 59 · Backtracking
Combination Sum
Problem
Given an array of candidates and a target, return all combinations where the chosen numbers sum to the target. Reuse of elements is allowed.
Approach
Backtracking + DFS: sort candidates; at each level choose current or skip; reuse allowed, so stay at the current index.
Time O(2^t)Space O(target)
How it works
- 1Sort candidates for pruning.
- 2DFS picks candidates from the current index (reuse allowed).
- 3Copy the path when the remainder hits zero.
Sample input / output
Input: 4 7 2 3 6 7 Output: [[2, 2, 3], [7]]
Constraints
1 <= candidates.length <= 30; distinct; 1 <= target <= 500.
Solution — read it, then walk it
Time O(2^t)Space O(target)Loops 1Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/26
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits