You are given an array of integers candidates, which may contain repeated values, and an integer target. Find all unique combinations of elements of candidates whose values sum to target.
Each element of candidates may be used only once in a combination. The result must not contain duplicate combinations.
Function Signature
def find_unique_combinations(candidates: list[int], target: int) -> list[list[int]]:
Rules
-
Each array position can be used at most once. Equal values at different positions are separate elements, so a value may appear in a combination as many times as it appears in
candidates
.
-
Two combinations are the same when they hold the same values with the same counts. Return each such combination once.
-
List the values inside each combination in non-decreasing order.
-
Sort the outer list in ascending lexicographic order, comparing combinations element by element the way Python compares lists.
-
Return an empty list when no combination sums to
target
.
Constraints
-
1 <= len(candidates) <= 100
-
1 <= candidates[i] <= 50
-
1 <= target <= 30
Examples
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
The two 1s are different elements, so they can appear together in [1,1,6]. With exactly one 1 the rest must sum to 7, which gives [1,2,5] and [1,7]. Without any 1 the only option is [2,6].
Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
There are three 2s, so [1,2,2] can be built from three different pairs of positions, but it is reported once. [5] uses the single 5.
Input: candidates = [1,1,1,1], target = 2
Output: [[1,1]]
Any two of the four 1s sum to 2. All six position pairs give the same values, so the answer holds one combination.