Given two integers n and k, return all possible combinations of k numbers chosen from the range ([1, n]).
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output: [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
Example 2:
Input: n = 1, k = 1
Output: [[1]]
This problem is a classic example of generating combinations. We can solve this using backtracking. We will explore all potential combinations by recursively adding elements to a current combination and ensuring that each combination is of length k.
Steps:
backtrack
to generate combinations.Here’s the implementation in Java:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), n, k, 1);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> current, int n, int k, int start) {
if (current.size() == k) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i <= n; i++) {
current.add(i);
backtrack(result, current, n, k, i + 1);
current.remove(current.size() - 1);
}
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.combine(4, 2)); // [[2, 4], [3, 4], [2, 3], [1, 2], [1, 3], [1, 4]]
System.out.println(sol.combine(1, 1)); // [[1]]
}
}
Thus, this solution is efficient for moderate values of n and k but may become impractical if n and k are very large.
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?