A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 216. Combination Sum III, the solution in this repository is mainly a backtracking solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. 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
- time: O((9!/(9-K)!)*K), there are P(9,K) combinations and the last recursion takes O(n) time
- space: O(K)
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. 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 win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- 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((9!/(9-K)!)*K), there are P(9,K) combinations and the last recursion takes O(n) time
- Space: O(K)
Guide
C++ Solution
Your submission
The accepted solution
01//backtracking
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Combination Sum III.
03//Memory Usage: 6.3 MB, less than 89.73% of C++ online submissions for Combination Sum III.
04//time: O((9!/(9-K)!)*K), there are P(9,K) combinations and the last recursion takes O(n) time
05//space: O(K)
06class Solution {
07public:
08 void backtrack(int k, int n, vector<int>& cur, vector<vector<int>>& ans){
09 if(cur.size() == k){
10 if(accumulate(cur.begin(), cur.end(), 0) == n){
11 ans.push_back(cur);
12 }
13 }else{
14 for(int i = (cur.empty() ? 1 : cur.back()+1); i <= 9; ++i){
15 cur.push_back(i);
16
17 backtrack(k, n, cur, ans);
18
19 cur.pop_back();
20 }
21 }
22 }
23
24 vector<vector<int>> combinationSum3(int k, int n) {
25 vector<int> cur;
26 vector<vector<int>> ans;
27
28 backtrack(k, n, cur, ans);
29
30 return ans;
31 }
32};
Cost