题目描述:
排列与组合是常用的数学方法,其中组合就是从n个元素中抽出r个元素(不分顺序且r≤n),我们可以简单地将n个元素理解为自然数1,2,…,n,从中任取r个数。
现要求你用递归的方法输出所有组合。
例如n=5,r=3,所有组合为:1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5
代码:
package lanqiao;import java.util.*;public class Main {static ArrayList<List<Integer>> list = new ArrayList<>();static LinkedList<Integer> ans = new LinkedList<>();public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt(); //元素int k = sc.nextInt(); //组合长度dfs(n,k,1);for(List<Integer> i : list){for(Integer j : i){System.out.printf("%3d",j);}System.out.println();}}public static List<List<Integer>> dfs(int n,int k,int startIndex){if(ans.size() == k){list.add(new ArrayList<>(ans));}for(int i = startIndex;i <= n;i ++){ans.add(i);//下一轮搜索,因为数字不能重复dfs(n,k,i + 1);ans.removeLast();}return list;}
}