#133 · Recursion and backtracking · Advanced · 125 XP · about 22 min
You have a list of different positive whole numbers, candidates, and a target total. Write combination_sum(candidates, target) that returns every combination of candidates adding up to exactly target, where each candidate can be used as many times as you like.
Order inside a combination does not matter: [2, 3, 3] and [3, 2, 3] are the same combination and must appear once. Write each combination as a list in increasing order, and return the combinations sorted, in Python's ordering of lists.
combination_sum([2, 3, 5], 8) # returns [[2, 2, 2, 2], [2, 3, 3], [3, 5]] combination_sum([7, 3, 2], 7) # returns [[2, 2, 3], [7]] combination_sum([4, 6], 5) # returns []
A total of 8 from 2, 3 and 5 can be made as four 2s, as a 2 and two 3s, or as a 3 and a 5.
1 <= len(candidates) <= 30, and the candidates are all different.1 <= candidates[i] <= 401 <= target <= 40Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.