Combinations
Backtracking
Last updated
Was this helpful?
Backtracking
Last updated
Was this helpful?
Given two integers n and k, return all possible combinations of knumbers out of 1 ... n.
You may return the answer in any order.
For example:
The for-loops and recursion method are very similar to the Subset problem, apart from the part that stops the DFS/recursion; for this problem it's when k = 0.
We can generate the subsets in pairs of k by decreasing k inside the recursion method. This is basically like saying "Hey we have 1 number (which is that specific number the for loop is on) so we can explore the other numbers in our recurrsion and while doing so, we'll decrease k."
The for-loop is the important factor that helps us traverse the "branches" for each number.
We are decreasing k in our recursion method which helps us keep track of how many numbers we can append to the subset list still.
Time: because of the combination formula and we multiply that by k because of our operation of copying the list in k time (since there is only k elements in the combination list)
Space: because this will be the max depth of the recursion call stack