If you are diving into the world of coding challenges, you might have encountered the "Combination Sum II" problem on LeetCode. This problem is not just about finding combinations but ensuring they are unique. In this blog post, we will explore how to solve this problem effectively, dissect the solution, and understand its time and space complexity in a better Way.
Problem Overview
The Combination Sum II problem asks you to find all unique combinations in a list of numbers that sum up to a specific target. Each number in the list can only be used once, and the solution must avoid duplicate combinations.
Example 1:
- Input:
candidates = [10,1,2,7,6,1,5]
,target = 8
- Output:[
[1,1,6], [1,2,5], [1,7], [2,6] ]
Example 2:
- Input:
candidates = [2,5,2,1,2]
,target = 5
- Output:
[ [1,2,2], [5] ]
C++ Code :-
How It Works
Sorting the Candidates:
- The
candidates
vector is sorted initially withsort(candidates.begin(), candidates.end())
. This sorting helps in easily skipping duplicates later on.
- The
Recursive Backtracking Function (
solve
):- Base Case: When
target
is 0, it means the current combinationv
adds up to the desired target. Hence,v
is added toans
. - Early Termination: If
target
becomes negative, it means the current path is invalid, so the function returns early. - Iterating and Skipping Duplicates: The loop starts from
index
to avoid recombination and skips over duplicates usingif (i > index && candidates[i] == candidates[i - 1]) continue;
. - Exploring New Combinations: The current number is added to the combination (
v.push_back(candidates[i])
), and the function recursively explores further possibilities by callingsolve
with the updated target and index. - Backtracking: After exploring the current path, the last added number is removed (
v.pop_back()
) to backtrack and explore other combinations.
- Base Case: When
Main Function (
combinationSum2
):- Initializes the combination vector
v
and the result vector 'ans'
. - Calls "
solve"
with the initial parameters to start the backtracking process. - Returns the '
ans'
vector containing all unique combinations that sum up to the target.
- Initializes the combination vector
Time and Space Complexity
Time Complexity:
- The time complexity of this algorithm is , where is the number of candidates. This is because, in the worst case, the algorithm explores all possible subsets of the input list. Although the exact number of calls depends on the specific input, it’s exponential in the number of candidates.
Space Complexity:
- The space complexity is for storing the current combination
v
and the recursive call stack. In the worst case, the depth of the recursion tree can go up to (the length of the candidates array), and the space required to store the current combination can also be .