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;
}
};
Difficulty
and has an acceptance rate of about 60% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 39: Combination Sum
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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