package LeetCode.backtrackpart01;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 77. 组合
* 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
* 你可以按 任何顺序 返回答案。
* 示例:
* 输入:n = 4, k = 2
* 输出:
* [ [2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
* */
public class Combinations_77 {
static List<List<Integer>> result = new ArrayList<>();
static LinkedList<Integer> path = new LinkedList<>();
public static void main(String[] args) {
List<List<Integer>> result = combine(4,2);
System.out.println(result);
}
public static List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}
/**
* 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
* @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
public static 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);
// 当i=2时,需要继续递归,然后判断长度已经到达终止条件,所以直接return了
//接着走 i=2 的下一步,回溯,将末尾数据弹走
path.removeLast();//
}
}
}