Algo-Sim › Recursion & Backtracking
Combination Sum II
Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Combinations that sum to a target, each candidate used once, when the input has repeats: Combination Sum with i + 1 and the Subsets II skip.
Problem
Given an array candidates (which may contain repeated values) and a target, return every distinct combination of candidates that adds up to target. Each element may be used at most once, and the answer must not contain the same combination twice.
Constraints
- 1 ≤ candidates.length ≤ 100
- 1 ≤ candidates[i] ≤ 50
- 1 ≤ target ≤ 30
Edge cases to test
- Duplicates in the candidates
- No combination
- The whole array sums to the target
Follow-up questions
- How does it differ from Combination Sum?
- Each candidate is used once (recurse with i + 1), and equal values at the same depth are skipped to avoid repeated combinations.
- Why sort first?
- Sorting groups duplicates for the skip rule and lets the loop break at the first candidate that overshoots.
Solution
Java
List<List<Integer>> result = new ArrayList<>();
List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtrack(candidates, target, 0, new ArrayList<>());
return result;
}
void backtrack(int[] cand, int remaining, int start, List<Integer> path) {
if (remaining == 0) {
result.add(new ArrayList<>(path));
return;
}
for (int i = start; i < cand.length; i++) {
if (i > start && cand[i] == cand[i - 1]) continue;
if (cand[i] > remaining) break;
path.add(cand[i]);
backtrack(cand, remaining - cand[i], i + 1, path);
path.remove(path.size() - 1);
}
}Python
def combination_sum2(candidates, target):
candidates = sorted(candidates)
result = []
def backtrack(remaining, start, path):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > remaining:
break
path.append(candidates[i])
backtrack(remaining - candidates[i], i + 1, path)
path.pop()
backtrack(target, 0, [])
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> result = {};
vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> path;
backtrack(candidates, target, 0, path);
return result;
}
void backtrack(vector<int> &cand, int remaining, int start, vector<int> &path) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int i = start; i < int(cand.size()); i++) {
if (i > start && cand[i] == cand[i - 1])
continue;
if (cand[i] > remaining)
break;
path.push_back(cand[i]);
backtrack(cand, remaining - cand[i], i + 1, path);
path.pop_back();
}
}
};
More Recursion & Backtracking problems
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Combinations (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)