Given two integers n
and k
, return all possible combinations of k
numbers out of the range [1, n]
.
You may return the combinations in any order.
Input: n = 4, k = 2
Output: [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
n
or k
be zero?
k
is zero, the result should be an empty list within a list: [[]]
.n
and k
?
1 <= k <= n <= 20
is a reasonable assumption for combinatorial problems.n
and k
are positive integers.1
to n
.#include <vector>
class Solution {
public:
void backtrack(int start, int n, int k, std::vector<int>& current, std::vector<std::vector<int>>& result) {
if (current.size() == k) {
result.push_back(current);
return;
}
for (int i = start; i <= n; ++i) {
current.push_back(i);
backtrack(i + 1, n, k, current, result);
current.pop_back(); // backtrack
}
}
std::vector<std::vector<int>> combine(int n, int k) {
std::vector<std::vector<int>> result;
std::vector<int> current;
backtrack(1, n, k, current, result);
return result;
}
};
By following the backtracking approach, we ensure that we explore all valid combinations efficiently while backtracking appropriately to explore other paths.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?