题目
题解
代码
import java.util.*;
public class code77 {
public static List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (n <= 0 || k <= 0 || n < k) {
return res;
}
List<Integer> list = new ArrayList<Integer>();
dfs(res, list, 0, 1, n, k);
return res;
}
public static void dfs(List<List<Integer>> res, List<Integer> list, int count, int start, int n, int k) {
if (count == k) {
res.add(new ArrayList<>(list));
return;
}
for (int i = start; i <= n - (k - list.size()) + 1; i++) {
list.add(i);
dfs(res, list, count + 1, i + 1, n, k);
list.remove(list.size() - 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
int k = sc.nextInt();
List<List<Integer>> res = combine(n, k);
System.out.println(res);
}
sc.close();
}
}