A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 39. Combination Sum, the solution in this repository is mainly a backtracking solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: backtracking.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are backtrack.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 12 ms, faster than 81.07% of C++ online submissions for Combination Sum.
02//Memory Usage: 8.8 MB, less than 100.00% of C++ online submissions for Combination Sum.
03
04class Solution {
05public:
06 int tgt;
07
08 void backtrack(vector<vector<int>>& combs, vector<int>& comb, vector<int>& candidates, int start){
09 int cursum = accumulate(comb.begin(), comb.end(), 0);
10 // cout << "cursum: " << cursum << endl;
11 if(cursum > tgt){
12 }else if(cursum == tgt){
13 combs.push_back(comb);
14 }else{
15 //we may reuse the last element
16 for(int i = max(0,start-1); i < candidates.size(); i++){
17 comb.push_back(candidates[i]);
18 // cout << i << endl;
19 backtrack(combs, comb, candidates, i+1);
20 comb.pop_back();
21 }
22 }
23 };
24
25 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
26 vector<vector<int>> combs;
27 vector<int> comb;
28 tgt = target;
29
30 backtrack(combs, comb, candidates, 0);
31
32 return combs;
33 }
34};
Cost