Combinations!
Given two integers n and k, return all possible combinations of the k numbers chosen from [1,n]
Considering that the problem requires all combinations, and given that the end of range n is constrained to the relatively low value of 20, this problem can be approached using brute-force, or backtracking (and without any dynamic programming).
Backtracking is a way to enumerate all possible solutions. It is like systematically traversing a maze, or a tree data-structure. It shares similarities with depth-first search.
First we initialize some variables in our main function. We make the given n and k values global variables nn and kk. We also initialize the vector of vectors that will store our solutions, and the vector current that stores the current solution we're working on.
int nn, kk;
vector<vector<int>> combine(int n, int k) {
nn=n;
kk=k;
vector<vector<int> > answer;
vector<int> current;
...
return answer;
}
Next we define the backtracking function we'll call. The parameters will be the current solution we're woking on curr, the number we're working on, and the solution.
void backtrack(vector<int>& curr, int firstNum, vector<vector<int> >& ans) {
...
}
We'll begin calling backtrack with an empty current vector, an empty answer, and a starting value of 1
backtrack(current, 1, answer);
In the backtracking function, we iterate from the firstnum value passed as an input up to the max value nn. Each time we push the iterative value onto the current vector, backtrack, and then pop. the value off of current.
for(int num=firstNum; num <= nn; num++) {
curr.push_back(num);
backtrack(curr, num+1, ans);
curr.pop_back();
}
Like DFS, there is a halting condition. In this case, if the current solution we're working on has reached size k. If so, push the answer onto the solution vector and then backtrack.
if(curr.size()==kk) {
ans.push_back(curr);
return;
}
Vanilla backtracking problem. User AlecLC recommended following up with Combo Sum, Permutations, Subsets, and Word Search
Thanks to the Editorial to get the ball rolling for backtracking problems
Comments
Post a Comment