77. Combinations (Medium)
https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Solutions
1.
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<Integer> track = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
getNext(0, n, k, track, ans);
return ans;
}
private void getNext(int depth, int n, int k, List<Integer> track, List<List<Integer>> ans) {
if (k == track.size()) {
// create a new copy, do not refer to it
List<Integer> solution = new ArrayList<>();
for (int x : track) {
solution.add(x);
}
ans.add(solution);
return;
}
for (int j = depth + 1; j <= n; j++) {
track.add(j);
getNext(j, n, k, track, ans);
track.remove(track.size()-1);
}
}
}
2.
class Solution2 {
public List<List<Integer>> combine(int n, int k) {
List<Integer> track = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
getNext(1, n, k, track, ans);
return ans;
}
private void getNext(int depth, int n, int k, List<Integer> track, List<List<Integer>> ans) {
if (track.size() == k) {
// create a new copy, do not refer to it
List<Integer> sol = new ArrayList<>(track);
ans.add(sol);
return;
}
// above code should not be place at the head of function, otherwise mistakes occurs
if (depth > n) {
return;
}
track.add(depth);
getNext(depth + 1, n, k, track, ans);
track.remove(track.size() - 1);
getNext(depth + 1, n, k, track, ans);
}
}