全排列(List)实现

package Java2012大赛;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*实现了n个数在m(n>=m)个位置上的全排列
 * */
public class 全排列List {
	static Set set = new HashSet();
	static int i;// 要排列的个数
	static int j;// 在几个位置排列
	static int num = j;// 一个定值
	static List list;
	static int count = 0;// 记录全排列的个数
	public static void main(String[] args) throws IOException {
//		File file = new File("E:" + File.separator + "txt" + File.separator
//				+ "全排列.txt");
		File file = new File("E:" + File.separator
			+ "全排列.txt");
		file.createNewFile();
		int i = Integer.parseInt(javax.swing.JOptionPane
				.showInputDialog("输入排列的个数"));
		list=new ArrayList();
		int j = Integer.parseInt(javax.swing.JOptionPane
				.showInputDialog("在几个位置排列"));
		for(int a=0;a<j;a++)
			list.add(0);
		num = j;
		fx(i, j, num);
		System.out.println(count);
	}

	private static void fx(int i, int j, int num) throws IOException {
		if (j == 1) {// 如果j==1
			for (int a = 1; a <= i; a++) {
				list.set(num - 1, a);
				for (int k = 0; k < num - 1; k++) {
					set.add(list.get(k));
				}
				set.add(list.get(num - 1));
				set.add(a);
				if (set.size() == num) {
					count++;
					System.out.println(list);
				}
				set.clear();
			}
			return;
		}
		j--;
		for (int a = 1; a <= i; a++) {
			list.set(num - j - 1, a);
			fx(i, j, num);
		}
	}
}

你可能感兴趣的:(全排列(List)实现)