Problem 40

Abstract / Summary

Given a list of numbers and a target, find all unique combinations that sum to the target using each number at most once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0040.cpp

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        map<int, set<multiset<int>>> dp;
        dp[0] = {{}};

        for (auto x : candidates)
        {
            auto next = dp;

            for (auto& level : dp)
                for (auto base : level.second)
                {
                    int sum = 0;
                    for (auto n : base)
                        sum += n;

                    if (sum + x > target)
                        continue;

                    base.insert(x);
                    next[sum + x].insert(move(base));
                }

            dp = move(next);
        }

        vector<vector<int>> result;
        for (auto base : dp[target])
        {
            vector<int> add({ base.begin(), base.end() });
            result.push_back(add);
        }

        return result;
    }
};
38 lines | 985 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the classic “combination sum II” problem: given a multiset of candidate integers and a target value, it returns all unique combinations where the chosen numbers sum to the target. Each candidate may be used at most once, and the result must not contain duplicate combinations. The algorithm builds combinations incrementally while maintaining a deduplicated collection of partial results keyed by their current sum.

Key Steps

Sorting the input

sort(candidates.begin(), candidates.end());

Sorting places equal values next to each other, which later enables the set containers to treat identical multisets as the same element. The ordered nature of the input also allows early termination when a partial sum would exceed the target.

Initializing the dynamic-programming map

map<int, set<multiset<int>>> dp;
dp[0] = {{}};

The map dp associates each achievable sum with a set of distinct multisets that realize that sum. The entry for sum 0 starts with a single empty multiset, representing the base case of selecting no numbers.

Iterating over each candidate

for (auto x : candidates)
{
    auto next = dp;
    // inner loops omitted for brevity
    dp = move(next);
}

For every candidate x, a copy of the current state (next) is created. The algorithm then attempts to extend every existing combination with x. After processing the candidate, dp is replaced by next using move semantics, which avoids an extra deep copy and keeps memory usage tight.

Extending existing combinations

for (auto& level : dp)
    for (auto base : level.second)
    {
        int sum = 0;
        for (auto n : base)
            sum += n;

        if (sum + x > target)
            continue;

        base.insert(x);
        next[sum + x].insert(move(base));
    }

The outer loop iterates over each recorded sum (level.first) and its associated set of multisets (level.second). For each base multiset, the current sum is recomputed by iterating over its elements. If adding the current candidate would exceed the target, the combination is discarded early. Otherwise, x is inserted into a copy of base, and the new multiset is placed into next under the updated sum key. The use of move(base) when inserting into the set transfers ownership of the temporary multiset, reducing allocation overhead.

Collecting the final results

vector<vector<int>> result;
for (auto base : dp[target])
{
    vector<int> add({ base.begin(), base.end() });
    result.push_back(add);
}

When all candidates have been processed, the map entry for the target sum contains every unique multiset that reaches the target. Each multiset is transformed into a vector<int> preserving the sorted order of elements, and the vectors are accumulated into the final result container.

Edge Cases Handled

When the input list is empty, the initial map contains only the sum 0 entry. Since no candidates are processed, the loop body never runs, and the final lookup dp[target] yields an empty set unless the target itself is zero. In the zero-target case, the algorithm returns a single empty combination, reflecting the mathematical fact that the empty set sums to zero.

Duplicate values in candidates are naturally de-duplicated by the set<multiset<int>> structure. Even if the same number appears multiple times, each distinct multiset of indices that leads to the same value composition is stored only once, preventing repeated output rows.

If a candidate value is larger than the target, the early continue guard (if (sum + x > target)) ensures that no combination involving that candidate is considered, effectively pruning impossible branches without extra recursion.

Performance Optimizations

The code leverages several C++ features to keep the execution efficient. Sorting the input once at the beginning enables early pruning of over-large sums and guarantees that the multisets stored in the set are ordered, which is required for proper deduplication.

The use of map<int, set<multiset<int>>> provides logarithmic access to the collection of partial results keyed by sum, allowing the algorithm to focus only on sums that have been reached so far.

Copy-on-write is avoided by creating a fresh next map for each candidate and then swapping it into dp with move. This pattern eliminates the need for deep copying of the entire state after each iteration.

When inserting a newly formed multiset into next, the code calls move(base). Moving the multiset transfers its internal storage to the destination set without allocating new memory for the elements, which reduces both time spent on allocations and overall memory pressure.

Finally, the reconstruction of the output vectors from multisets uses range-based construction (vector<int> add({ base.begin(), base.end() });). Because the multisets are already sorted, the resulting vectors are produced in the required non-decreasing order without additional sorting steps.

These choices collectively keep the algorithm’s runtime proportional to the number of unique combination states that actually appear, while minimizing overhead from copying and memory allocation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big treasure chest full of different colored building blocks, and each block has a number written on it. Your mission is to find every possible group of these blocks that adds up to a secret target number. To make it easier, you first sort all the blocks by their numbers so they are in a neat line from smallest to largest.

You start with a special blank space that represents a sum of zero, because you have not picked any blocks yet. Then, you look at each block one by one. For every block you see, you think about all the groups you have already built. You take those existing groups and try adding this new block to each of them. If the new sum is still smaller than or equal to your target number, you keep that new group to use later.

As you go through every block in the chest, your collection of groups grows bigger. You are very careful to make sure you do not find the same group twice by using a special organizer to keep the groups tidy. Once you have looked at every single block, you peek inside your organizer to find all the groups that add up to the exact target number you were looking for. Those are your winning combinations, and you can put them all together on a tray to show off your hard work.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 4 | μ = 4.54 | σ = 2.03

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
bujosa Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
bujosa Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
60 links | 42 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Combination Sum II - Backtracking - Leetcode 40 - Python'
NeetCode 16 mins
Combination Sum II - Backtracking - Leetcode 40 - Python
YouTube video 'Combination Sum II - Leetcode 40 - Python'
NeetCodeIO 16 mins
Combination Sum II - Leetcode 40 - Python
YouTube video 'Combination Sum II | Simple Khandani Template | Leetcode 40 | codestorywithMIK'
codestorywithMIK 27 mins
Combination Sum II | Simple Khandani Template | Leetcode 40 | codestorywithMIK
YouTube video 'combination sum ii | combination sum ii leetcode | leetcode 40 | backtracking | Facebook Amazon'
Naresh Gupta 9 mins
combination sum ii | combination sum ii leetcode | leetcode 40 | backtracking | Facebook Amazon
YouTube video '✅ Combination Sum II - LeetCode 40 - Union Find - Optimized - Explained in Detail'
Leet Logics 11 mins
✅ Combination Sum II - LeetCode 40 - Union Find - Optimized - Explained in Detail
YouTube video 'Combination Sum II - LeetCode 40 - Python  #backtracking #leetcode #combinations'
Deepti Talesra 21 mins
Combination Sum II - LeetCode 40 - Python #backtracking #leetcode #combinations
YouTube video 'LeetCode 40. Combination Sum II Explanation and Solution'
happygirlzt 5 mins
LeetCode 40. Combination Sum II Explanation and Solution
YouTube video 'LeetCode: 40. Combination Sum II (Visualized)'
Code With Zi 17 mins
LeetCode: 40. Combination Sum II (Visualized)
YouTube video 'LeetCode 40. Combination Sum II 中文解释 Chinese Version'
happygirlzt 6 mins
LeetCode 40. Combination Sum II 中文解释 Chinese Version
YouTube video 'Combination Sum II Python Solution - LeetCode #40'
Professor Oakes 7 mins
Combination Sum II Python Solution - LeetCode #40
YouTube video 'Combination Sum II  (LeetCode 40) (Recursion, Backtracking)'
CodeWithARB 26 mins
Combination Sum II (LeetCode 40) (Recursion, Backtracking)
YouTube video '🎉 Day 100: Combination Sum II Explained | Leetcode 40 | Backtracking Python | srkcodes'
Srk Codes 8 mins
🎉 Day 100: Combination Sum II Explained | Leetcode 40 | Backtracking Python | srkcodes
YouTube video 'Daily Leetcode #1596: Aug 13, 2024 - 40. Combination Sum II'
Programming Live with Larry 18 mins
Daily Leetcode #1596: Aug 13, 2024 - 40. Combination Sum II
YouTube video 'Solve 40. Combination Sum II - Java & C++ Solutions | August Challenge'
Mayur Programming Club 22 mins
Solve 40. Combination Sum II - Java & C++ Solutions | August Challenge
YouTube video 'LeetCode 40 - Combination Sum II | Recursion & Backtracking JavaScript Solution'
Web Coder Abhishek 8 mins
LeetCode 40 - Combination Sum II | Recursion & Backtracking JavaScript Solution
YouTube video 'LeetCode 40 - Combination Sum II - Java'
Alpha-Code 18 mins
LeetCode 40 - Combination Sum II - Java
YouTube video 'LeetCode 40: Combination Sum II | C# Solution | Backtracking with Duplicates |'
Code Scribbler 10 mins
LeetCode 40: Combination Sum II | C# Solution | Backtracking with Duplicates |
YouTube video 'Combination Sum II | Leetcode 40 | BackTracking | Java Code | Developer Coder'
Developer Coder 15 mins
Combination Sum II | Leetcode 40 | BackTracking | Java Code | Developer Coder
YouTube video '69. Leetcode 40. Combination Sum II : Javascript'
Web Fusion with Bharadwaj 18 mins
69. Leetcode 40. Combination Sum II : Javascript
YouTube video 'Amazon Coding Interview Question | Leetcode 40 | Combination Sum II'
WorkWithGoogler 7 mins
Amazon Coding Interview Question | Leetcode 40 | Combination Sum II
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality