题目描述
排列与组合是常用的数学方法,其中组合就是从n个元素中抽出r个元素(不分顺序且r≤n),我们可以简单地将n个元素理解为自然数1,2,…,n,从中任取r个数。
现要求你输出所有组合。
例如n=5,r=3,所有组合为:
123,124,125,134,135,145,234,235,245,345
输入格式
一行两个自然数n,r(1<n<21,0≤r≤n)。
输出格式
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
**注意哦!输出时,每个数字需要3个场宽,pascal可以这样:
write(ans:3);
输入输出样例
输入
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.*;
public class text002 {
public static int a = 0;
public static int b = 0;
public static void main(String args[]) throws Exception {
Scanner cin=new Scanner(System.in);
a = cin.nextInt();
b = cin.nextInt();
int[] c = new int[b];
int d = 0;
int e = 0;
int g = 1;
fac(b, c,d,e,g,b);
}
public static void fac(int b1, int[] c,int d,int e,int g,int b3) {
int e2 = e;
for(int i = e; i < a; i++) {
c[d] = i;
if(b1-1 != 0) {
int b2 = b1;
int d1 = d;
int e1 = e2;
int g1 = g;
int b4 = b2;
fac(--b4,c,++d1, ++e1,++g1,b3);
}
if(g == b3) {
for(int n = 0; n < b; n++) {
if(c[n]+1 <10) {
System.out.print(" "+(c[n]+1));
}else if(c[n]+1 >= 10) {
System.out.print(" "+(c[n]+1));
}
}
System.out.println();
}
e2++;
}
}
}
但是在10个测试样例中,最后一个会超时!!本萌新力尽了,呜呜~