Problem
Given two integers $n$ and $k$, return all possible combinations of $k$ numbers out of $1$ … $n$.
Example:
1 |
|
Explanation
-
When $n = 4$ and $k = 2$, we can only have two numbers in the sublist. If for the first number we choose $1$, then the second number we can have $2$, $3$, $4$. If for the first number we choose $3$, we can only have $4$ as the second number.
-
We can see that we need to use iteration to choose the first number, then for the second number, we start looping from the first number plus one.
-
So, we need to have a
start
variable,result
,temp
,n
andk
variables. -
The base case is whenever the
temp
variable already have $k$ numbers, we return.
Solution
1 |
|