(Java实现) 组合的输出

问题 B: 【递归入门】组合的输出
时间限制: 1 Sec 内存限制: 128 MB
题目描述
排列与组合是常用的数学方法,其中组合就是从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

输入
一行两个自然数n、r ( 1 < n < 21,1 < = r < = n )。

输出
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,所有的组合也按字典顺序。

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;


public class zuhedeshuchu {
	static Set<String> set = new HashSet<String>();
	public static int r=0,n=0;
	public static boolean [] bool;
	public static int [] num1;
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		 n = sc.nextInt();
		r=sc.nextInt();
		sc.close();
		 int [] num = new int [r+1];
		 num1 = new int [r+1];
		 bool = new boolean [n+1];
		 String s = "";
		 f(1,num);
		Iterator it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
	public static void f(int a,int [] num){
		if(a==r+1){
			num1=num.clone();
			Arrays.sort(num1);
			String s = "";
			for (int i = 1; i < num1.length; i++) {
				s=s+num1[i];
			}
			set.add(s);
			return;
		}
		for (int i = 1; i <=n; i++) {
 			if(!bool[i]){
				bool[i]=true;
				num[a]=i;
				f(a+1,num);
				num[a]=0;
				bool[i]=false;
			}
		}
	}
}

原文地址:https://www.cnblogs.com/a1439775520/p/13079125.html