77. Combinations
Description
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.
Approach
BackTracking
- Initialize two global parameters
result
(store the final result of combinations) andpath
(store the current combination). - Intialize a recursive function with parameters
n
,k
andstartIndex
(control the elements that can be included in the current combination). - If the size of
path
equals tok
, which means a combinations is found, addpath
toresult
. - Loop from
startIndex
ton - (k - path.size()) + 1
(ensures that the loop doesn’t go beyond the maximum possible value for a valid combination with the current elements):- add the current loop index to
path
. - Recursively call the function with
startIndex + 1
- Remove the last integer in
path
to backtrack.
- add the current loop index to
Soltuion
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backTracking(n, k, 1);
return result;
}
private void backTracking(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);
backTracking(n, k, i + 1);
path.remove(path.size() - 1);
}
}
}
Reference: https://programmercarl.com/