Backtracking Algorithm for Combinations
Problem Description
Given two integers n and k, return all possible comibnations of k numbers out of 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]]
Constraints:
1 <= n <= 201 <= k <= n
Solution
We can use backtracking to generate all combinations. The width of the recursion tree is n, and the depth is k.
Apporach 1: Without Pruning
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> current = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtrack(n, k, 1);
return result;
}
private void backtrack(int n, int k, int startIndex) {
if (current.size() == k) {
result.add(new ArrayList<>(current));
return;
}
for (int i = startIndex; i <= n; i++) {
current.add(i);
backtrack(n, k, i + 1);
current.removeLast();
}
}
}
Approach 2: With Pruning
The number of remaining elements needed is k - current.size(). Therefore, the last starting index should be at most n - (k - current.size()) + 1 to have enough elements.
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}
private void combineHelper(int n, int k, int startIndex) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
path.add(i);
combineHelper(n, k, i + 1);
path.removeLast();
}
}
}