试题来源:牛客网(https://www.nowcoder.com/test/30440590/summary)
有个物品可供选择,必须选择其中
个物品,请按字典序顺序输出所有选取方案的物品编号
与
与
等被认为是同一种方案,输出字典序最小的
即可
输入描述:

输出描述:
对于每组输入样例,按字典序输出所有方案选择物品的编号,每种方案占一行
输入例子1:
输出例子1:
输入例子2:
输出例子2:
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
参考答案:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static ArrayList<Stack<Integer>> res = new ArrayList<>();
public static void main(String[] args) throws IOException {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int m = sc.nextInt();
test(n,m);
}
public static void test(int n,int m){
dfs(n,m,1, new Stack<Integer>());
for(Stack<Integer> stack: res){
for(Integer elem : stack)
System.out.print(elem + " ");
System.out.println();
}
}
private static void dfs(int n, int m, int depth, Stack<Integer> stack) {
if(stack.size() == m){
res.add((Stack<Integer>)stack.clone());
return;
}
for(int i = depth; i <= n; i++){
stack.push(i);
dfs(n, m, i + 1, stack);
stack.pop();
}
}
}