InferenceAI

Enter at least two characters to search.

Start free

Combination Totals

mediumRecursion & Backtracking25 min25 XP

Given distinct positive candidates and a target, return every combination (each value may be used any number of times) that sums to target. Sort each combination ascending and return them in lexicographic order.

Constraints

  • 1≤1 \le target ≤40\le 40

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[2,3,6,7],7]
TASKcombination_totals()
EXPECTED OUTPUT[[2,2,3],[7]]

Start with the input values shown in this example.

Example 1 of 3

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

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

Explanation: classic

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

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

Explanation: several answers

Input: candidates = [2], target = 1

Output: []

Explanation: impossible

Hint 1

Recurse with a start index so each combination is built in non-decreasing order.

Hint 2

Stop exploring once the running sum exceeds the target.

Topics

DSARecursion & BacktrackingPython