您的位置:首页 > 编程语言 > Java开发

Java实现的全排列和排列

2014-03-22 11:17 399 查看
关于全排列和排列的问题已经困扰我n久了,虽然在组合数学中很简单,但是要想编程来实现还真不那么简单。排列组合的方法在做算法题的时候经常能够遇到,主要是对结果的所有可能进行穷举,穷举的方法一般都离不开排列和组合。下面给出一个比较好的用递归实现的全排列和排列代码,个人认为还是比较容易理解的。

全排列--Java实现

public class AllSort{

public static void main(String[] args) {

char buf[]={'a','b','c'};

perm(buf,0,buf.length-1);

}

public static void perm(char[] buf,int start,int end){

if(start==end){//当只要求对数组中一个字母进行全排列时,只要就按该数组输出即可(特殊情况)

for(int i=0;i<=end;i++){

System.out.print(buf[i]);

}

System.out.println();

}

else{//多个字母全排列(普遍情况)

for(int i=start;i<=end;i++){//(让指针start分别指向每一个数)

char temp=buf[start];//交换数组第一个元素与后续的元素

buf[start]=buf[i];

buf[i]=temp;

perm(buf,start+1,end);//后续元素递归全排列

temp=buf[start];//将交换后的数组还原

buf[start]=buf[i];

buf[i]=temp;

}

}

}

}

排列--Java实现

import java.util.*;

public class AllSort{

static int count = 0;

static char[] buf = {'1', '2', '3', '4'};

static ArrayList<String> list = new ArrayList<String>();

public static void main(String[] args) {

select(buf, list, 3);

for(String str : list){

char[] temp = str.toCharArray();

//perm(temp,0,temp.length-1);

System.out.println(str);

}

System.out.println("In total: "+ count);

}

public static void select(char[] source, ArrayList<String> arrayList, int num){

int l = source.length;

char[] temp = new char[num];

System.arraycopy(source, 0, temp, 0, num);

arrayList.add(new String(temp));

for(int i=num; i<l; i++){

for (int j=0; j<num; j++){

char tempChar = temp[j];

temp[j] = source[i];

arrayList.add(new String(temp));

temp[j] = tempChar;

}

}

}

public static void perm(char[] buf, int start, int end){

if(start==end){//当只要求对数组中一个字母进行全排列时,只要就按该数组输出即可

for(int i=0;i<=end;i++){

System.out.print(buf[i]);

}

count ++;

System.out.println();

}

else{//多个字母全排列

for(int i=start;i<=end;i++){

char temp=buf[start];//交换数组第一个元素与后续的元素

buf[start]=buf[i];

buf[i]=temp;

perm(buf,start+1,end);//后续元素递归全排列

temp=buf[start];//将交换后的数组还原

buf[start]=buf[i];

buf[i]=temp;

}

}

}

}

全排列的算法是一个基础,排列算法在它的基础上增加了选数过程(select),即先选后排。这里面主要是用到了一个递归的思想, 利用递归法来做这题关键下几点:

1.普通情况-取出序列中的一个数并且将剩下的序列全排列

2.特殊情况-序列中只剩一个数,则全排列就是其自身。将增个获得的序列输出。

3.在不止一个数的情况下,该位要分别交换剩下的数(例如:两个数A,B 则有两种情况,一个是AB 一个是BA)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: