Combination Sum II
LeetCode 40 | Difficulty: Mediumβ
MediumProblem Descriptionβ
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.
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]
]
Constraints:
- `1 <= candidates.length <= 100`
- `1 <= candidates[i] <= 50`
- `1 <= target <= 30`
Topics: Array, Backtracking
Approachβ
Backtrackingβ
Explore all candidates by building solutions incrementally. At each step, choose an option, explore further, then unchoose (backtrack) to try the next option. Prune branches that can't lead to valid solutions.
When to use
Generate all combinations/permutations, or find solutions that satisfy constraints.
Solutionsβ
Solution 1: C# (Best: 522 ms)β
| Metric | Value |
|---|---|
| Runtime | 522 ms |
| Memory | N/A |
| Date | 2018-01-21 |
Solution
public class Solution {
public IList<IList<int>> CombinationSum2(int[] candidates, int target) {
List<IList<int>> dp = new List<System.Collections.Generic.IList<int>>();
Array.Sort(candidates);
backtrack2(dp, new List<int>(), candidates, target, 0);
return dp;
}
public void backtrack2(List<IList<int>> dp, List<int> templist, int[] candidates, int target, int start)
{
if(target<0) return;
else if (target == 0)
{
dp.Add(templist.ToList());
}
else
{
for (int i = start; i < candidates.Length; i++)
{
if(i>start && candidates[i-1]==candidates[i]) continue;
templist.Add(candidates[i]);
backtrack2(dp, templist, candidates, target - candidates[i], i+1);
templist.RemoveAt(templist.Count-1);
}
}
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Backtracking | $O(n! or 2^n)$ | $O(n)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Identify pruning conditions early to avoid exploring invalid branches.