Notes
Some useful notes? or just my thinkings.
A conclusion of BackTracking
First
Backtracking is not always efficient because it examines every possibility and checks if the result satisfies the requirement.
What is backtracking? How to write?
The backtracking, in my opinion, just provides a way of iterating into some situations that we can’t iterate.
It might be hard to understand this sentence. Here is an example:
Problem:
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
Input:
n = 4, k = 2
Output:
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation:
There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e.,
[1,2] and [2,1] are considered to be the same.
If k == 2, we might want to think:
“Okay, we need to choose 2 numbers from [1, n] and form a combination. Why don't I just use 2 for loops and get every combination?”
Brutal force approach
vector<vector<int>> ans;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
ans.push_back(vector<int>{i, j});
}
}
But what if k is larger? Iteration will not always work. So, backtracking is a solution for this.
Actually, backtracking is a kind of recursion. We add an element → do something → then delete that element.
Backtracking solution
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> cur = vector<int>();
vector<vector<int>> ans = vector<vector<int>>();
addAll(n, 0, k, cur, ans);
return ans;
}
void addAll(int& n, int i, int k, vector<int>& prev, vector<vector<int>>& ans) {
if (k == 0) {
ans.push_back(prev);
return;
}
i++;
for (i; i <= n - k + 1; i++) {
prev.push_back(i);
addAll(n, i, k-1, prev, ans);
prev.pop_back();
}
}
};
Explanation
- i → the current index
- k → the required length of the answer (remaining elements needed)
- cur → the current vector of int sequence
- ans → the final answer (contains many cur)
Process:
- Base case: if k == 0, meaning cur reached the required length, push it into ans.
- Recursion: each time we push_back current int to cur, then recurse deeper.
- After recursion returns, we pop_back to restore the state.
Example recursion steps:
- when i = 0, push nums[0] → cur = [nums[0]]
- recurse deeper
- when i = 1, push nums[1] → cur = [nums[0], nums[1]]
- keep recursion...
- when returning, pop_back so that we can explore other branches
- continue the loop until i = n - k + 1 (this pruning improves performance).
- Finally, we get all answers stored in ans!
Conclusion
During the study of backtracking, I learned a lot about different strategies of calculating and pruning.
I am really proud of myself because I passed N-Queens with just one submission! 🎉
Backtracking is a way to solve some questions that might be separated into a lot of “layers,” but it might not be the fastest one.
Finally, I will keep learning algorithms and data structures!