Combination Sum II: Unique Combinations with Duplicates

Day - 60 Combination Sum II The problem - Given array (may contain duplicates) and target, return all unique combinations that sum to target. Each number can be used at most once. Example : candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]] Brute Force - Generate all combinations and filter duplicates, exponential and inefficient. Approach Used - •) Sort the candidates array. •) Call findCombinations(ind, arr, target, ans, ds). •) Base case, if target == 0, found valid combination, add new ArrayList(ds) to ans and return. •) Recursive case, for loop from ind to arr.length 1 - If i > ind && arr[i] == arr[i-1], skip it as it is duplicate. 2 - If arr[i] > target, break 3 - Add arr[i] to ds, recurse with i+1, findCombinations(i + 1, arr, target - arr[i], ans, ds). 4 - Backtrack: remove arr[i] from ds. Complexity - Time - O(2^n), we skip duplicates and terminate early. Space - O(n), recursion depth. Note - Sort array, skip duplicates at same recursion level to avoid duplicate combinations. Sorting groups duplicates together, making it easy to detect and skip them with the condition arr[i] == arr[i-1]. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories