</>

40. Combination Sum II

Medium NeetCode 150
Backtracking Time O(N^T/M) Space O(T/M)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Backtracking
Time
O(N^T/M)
Space
O(T/M)

Standard Solution (C++)

SummaryGiven a list of candidate integers that may contain duplicates and a target value, find all unique combinations of candidates that sum exactly to the target, where each candidate may only be used once.

Approach
  • Sort the candidates first so duplicates are adjacent and early pruning is possible when a value exceeds the remaining target.
  • Use backtracking with a for loop: at each recursion level, iterate over candidates starting from the current index.
  • To avoid duplicate combinations at the same recursion level, skip over a candidate when it equals the previous candidate and the previous one was not chosen at this level (i.e., i > start && candidates[i] == candidates[i-1]).
  • Pruning: because the array is sorted, break immediately when candidates[i] > remaining target.
  • Each recursive call advances the start index by one past the chosen element, preventing reuse of the same instance.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
    void backtrack(vector<int>& candidates, int target, int start,
                   vector<int>& current, vector<vector<int>>& result) {
        if (target == 0) {
            result.push_back(current);
            return;
        }
        for (int i = start; i < (int)candidates.size(); ++i) {
            // Pruning: sorted array means all subsequent values are also too large
            if (candidates[i] > target) break;
            // Skip duplicates at the same recursion level
            if (i > start && candidates[i] == candidates[i - 1]) continue;
            current.push_back(candidates[i]);
            backtrack(candidates, target - candidates[i], i + 1, current, result);
            current.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> result;
        vector<int> current;
        backtrack(candidates, target, 0, current, result);
        return result;
    }
};
Time O(2^n) in the worst case (each element included or excluded), though sorting and pruning make the practical runtime much better for typical inputs Space O(n) for the recursion stack depth and the current combination buffer (excluding the output)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    void find(vector<vector<int>>& result, vector<int>& cur, vector<int>& candidates, int target, int idx){
        if(target==0){
            result.push_back(cur);
            return;
        }

        if(target<0 || idx>=candidates.size() || candidates[idx]>target){
            return;
        }

        cur.push_back(candidates[idx]);
        find(result, cur, candidates, target-candidates[idx], idx+1);
        cur.pop_back();
        int next_idx=idx+1;
        while(next_idx<candidates.size() && candidates[next_idx]==candidates[next_idx-1]){
            ++next_idx;
        }
        find(result, cur, candidates, target, next_idx);
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        vector<int> cur;

        std::sort(candidates.begin(), candidates.end());
        find(result, cur, candidates, target, 0);
        return result;
    }
};

// Time Complexity: O(N^T/M) where N is the number of candidates, T is the target, M is the minimum candidate
// Space Complexity: O(T/M)
Time O(N^T/M) Space O(T/M)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern