This problem looks busy at first, but the accepted solution is built around one steady invariant. For 77. Combinations, the solution in this repository is mainly a backtracking solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. 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.
The notes already sitting in the source point us in the right direction:
- 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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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//backtracking
02//Runtime: 36 ms, faster than 73.39% of C++ online submissions for Combinations.
03//Memory Usage: 9.3 MB, less than 61.50% of C++ online submissions for Combinations.
04class Solution {
05public:
06 int n, k;
07
08 void backtrack(int start, vector<int>& comb, vector<vector<int>>& combs){
09 if(comb.size() == k){
10 combs.push_back(comb);
11 }else{
12 for(int i = start; i <= n; ++i){
13 comb.push_back(i);
14 backtrack(i+1, comb, combs);
15 comb.pop_back();
16 }
17 }
18 }
19
20 vector<vector<int>> combine(int n, int k) {
21 this->n = n;
22 this->k = k;
23
24 vector<int> comb;
25 vector<vector<int>> combs;
26
27 backtrack(1, comb, combs);
28
29 return combs;
30 }
31};
Cost