summary:
combinations | backtrack
package myapp.kit.leetcode.top200;
import java.util.ArrayList;
import java.util.List;
/**
*
* 77
* 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],
* ]
*
*
* @author huangdingsheng
* @version 1.0, 2020/7/9
*/
public class combinations_77 {
List<List<Integer>> answer;
public List<List<Integer>> combine(int n, int k) {
answer = new ArrayList<>();
backtrack(n, k, 1, new ArrayList<>());
return answer;
}
private void backtrack(int n, int k, int idx, List<Integer> path) {
if (path.size() == k) {
answer.add(new ArrayList<>(path));
return;
}
for (int i = idx; i <= n; i++) {
path.add(i);
backtrack(n, k, i + 1, path);
path.remove(path.size() - 1);
}
}
}