一般来说,从n个不同的元素中任取m(m≤n)个元素为一组,叫作从n个不同元素中取
出m个元素的一个组合,我们把有关求组合的个数的问题叫作组合问题。
现有n个数,从中选出m个数,试输出所有组合方案。
【输入格式】
输入两个整数/和1(0<m<n≤20)。
【输出格式】
按字典序输出所有组合方案。
例如:
输入格式: 5 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
代码:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int num = 5; //可进行修改
public static int length = 3; //可进行修改
public static List<Integer> a=new ArrayList<>();
public static int visited[]=new int[num+1];
public static void main(String[] args) {
for(int i=1;i<=num;i++){
a.add(i); //a集合存放1~num这些数字
}
List<Integer> result = new ArrayList<>(); //存放结果
dfs(1,num,length,0,a,visited,result);
}
//start的妙用: 保证依次按大小输出,避免结果重复输出(如:1 2 3, 1 3 2)
public static void dfs(int start,int num,int length,int nowlength,List<Integer> a,int visited[],List<Integer> result) {
if(nowlength==length){ //nowlength用来记住当前长度
for(int i:result){
System.out.print(i+" ");
}
System.out.println();
return;
}
if (nowlength > length) { //注意返回条件
return;
}
for (int i = start; i <= num; i++) {
if (visited[i] == 0) { //每次用完标记为1
result.add(i);
visited[i] = 1;
dfs(i,num,length,nowlength+1,a,visited,result);
result.remove(result.size()-1); //回溯
visited[i] = 0;
}
}
}
}