Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]
1 <= candidates.length <= 1001 <= candidates[i] <= 501 <= target <= 30The problem is to find all unique combinations of numbers that add up to a given target. Each number in the array can be used only once. For this, we can use a backtracking approach. First, we sort the array to make it easier to handle duplicates and to potentially stop early when the remaining candidates are all larger than the target left to achieve. By sorting, we also ensure that duplicates are adjacent, which allows us to easily skip over them.
This approach is similar to Approach 1 but adds a further optimization to stop early in the loop. By stopping early once we encounter candidates larger than the current remaining target (after checking the first element due to sorted order), we avoid unnecessary recursive calls.