LeetCode 77. Combinations
Question
Given two integers n
and k
, return all possible combinations of k
numbers out of the range [1, n]
.
You may return the answer in any order.
Example 1:
1 | Input: n = 4, k = 2 |
Example 2:
1 | Input: n = 1, k = 1 |
Constraints:
1 <= n <= 20
1 <= k <= n
Source: https://leetcode.com/problems/combinations/
Solution
The following code is based on the append solution of LeetCode 47. Permutations II. Why not swap-based solution? Because available elements in this question are not a fixed set but can be different subsets of [1, n]
.
Because combinations do not care about order, we can get combinations by restricting permutations to an ascending order. It is ok if the value on current position is too large to leave enough space for deeper layers. DFS paths just safely return to last layer before reach kth layer (leave layer).
1 | // start is the smallest valid value for current position |
LeetCode 77. Combinations