试题来源:牛客网(https://www.nowcoder.com/test/30440590/summary

8、阿里 - 图2个物品可供选择,必须选择其中8、阿里 - 图3个物品,请按字典序顺序输出所有选取方案的物品编号
8、阿里 - 图48、阿里 - 图58、阿里 - 图6等被认为是同一种方案,输出字典序最小的8、阿里 - 图7即可

输入描述:
image.png

输出描述:

对于每组输入样例,按字典序输出所有方案选择物品的编号,每种方案占一行

输入例子1:

4 1

输出例子1:

1
2
3
4

输入例子2:

5 2

输出例子2:

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

参考答案:

  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5. public class Main {
  6. public static ArrayList<Stack<Integer>> res = new ArrayList<>();
  7. public static void main(String[] args) throws IOException {
  8. Scanner sc =new Scanner(System.in);
  9. int n =sc.nextInt();
  10. int m = sc.nextInt();
  11. test(n,m);
  12. }
  13. public static void test(int n,int m){
  14. dfs(n,m,1, new Stack<Integer>());
  15. for(Stack<Integer> stack: res){
  16. for(Integer elem : stack)
  17. System.out.print(elem + " ");
  18. System.out.println();
  19. }
  20. }
  21. private static void dfs(int n, int m, int depth, Stack<Integer> stack) {
  22. if(stack.size() == m){
  23. res.add((Stack<Integer>)stack.clone());
  24. return;
  25. }
  26. for(int i = depth; i <= n; i++){
  27. stack.push(i);
  28. dfs(n, m, i + 1, stack);
  29. stack.pop();
  30. }
  31. }
  32. }