package com.example.lettcode.dailyexercises;
import java.util.ArrayList;
import java.util.List;
/**
* @Class Combine
* @Description 77 组合
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
* <p>
* 示例:
* 输入: n = 4, k = 2
* 输出:
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
* @Author
* @Date 2020/9/11
**/
public class Combine {
public static List<List<Integer>> combine(int n, int k) {
if (k > n) return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
recur(res, integers, n, k, 1);
return res;
}
// 回溯+递归
public static void recur(List<List<Integer>> res, List<Integer> integers, int n, int k, int idx) {
if (integers.size() == k) {
res.add(new ArrayList<>(integers));
return;
}
if (idx > n) {
return;
}
for (int i = idx; i <= n; i++) {
integers.add(i);
recur(res, integers, n, k, i + 1);
integers.remove(integers.size() - 1);
}
}
public static void main(String[] args) {
int n = 4;
int k = 2;
List<List<Integer>> res = combine(n, k);
System.out.println("Combine demo01 result:");
for (List<Integer> integerList : res) {
System.out.println();
for (Integer integer : integerList) {
System.out.print("," + integer);
}
}
}
}