You have a list of distinct positive integers, candidates, and a number target. Return every way to pick numbers from candidates that add up to exactly target. You may pick the same number as many times as you like.
A combination is decided by how many times it uses each number, not by the order you picked them in: [2,3,3] and [3,2,3] are the same combination, so list it only once.
You may return the combinations in any order, and the numbers inside each combination in any order too.
3 + 5 = 8, and 4 used twice makes 8. Two 3s would leave 2, which no candidate can fill.
Five 2s, two 2s with a 6, or two 5s.
[]
Every sum of 4s and 6s is even, so 9 can't be reached.
Constraints
1 <= candidates.length <= 302 <= candidates[i] <= 40candidates are all different.1 <= target <= 40150 combinations to return.To list each combination once, build it in one fixed order: go through the candidates in order, decide how many times to use each, and never go back to an earlier one. Then [2,3] and [3,2] can't both appear.
Think of the answer as a shopping list: how many of each candidate to buy so the bill comes to exactly target. Building a list one number at a time is a search with choices, so it suits backtracking: add a number, see where that leads, take it back, try another.
Time O(n^(T/M + 1))Space O(T/M) besides the answer
The full walkthrough and code are part of Premium