今天在阅读《Java数据结构与算法 第二版》的时候,看到了一个关于全排列的问题。给出的例子是如何排列出 字母c,a,t所有的不同组合。我按照递归的思路写了一下,成功运行。大致思路是,固定第一个元素,把剩余的全排列,然后数组向左轮转(最左边的转到最右边)然后重复这个过程直到数组中的每一个元素都出现在了第一的位置。
下面是代码:
输出结果:1234 1243 1342 1324 1423 1432 2341 2314 2413 2431 2134 2143 3412 3421 3124 3142 3241 3214 4123 4132 4231 4213 4312 4321
写完后上网一搜全排列,又发现了一些关于这个问题的进一步说明,有多种算法可实现,包括迭代的算法,有兴趣的童鞋可以上网搜一下,了解了解。
下面是代码:
package com.luxury.algorithm.recursion;
/**
* @author luxury_zh
* work out all the arrangements of the given numbers.It is a recursion
* algorithm which works like this:fix the first left number of the
* remaining array(at the beginning,it's just the given array) then arrange
* the right numbers.Next,the important thing is a rotation after one
* arrangement. Rotation means moving every element to its previous position
* (the first left element moves to the rightmost)
* Do the same steps until there is only one number in the remaining array.
*/
public class FullArray {
public static int[] array={1,2,3,4};
public static void main(String args[])
{
//execute the algorithm
doArrange(array.length);
}
public static void doArrange(int remainingSize)
{
if(remainingSize==1)
{
//print out the array
display(array);
System.out.print(" ");
return;
}
for(int i=0;i<remainingSize;i++)
{
//recursion:arrange the remaining numbers
doArrange(remainingSize-1);
//do rotation after one arrangement
rotate(remainingSize);
}
}
public static void display(int[] array)
{
for(int e : array)
System.out.print(e);
}
public static void rotate(int remainingSize)
{
int length=array.length;
int firstLeft=array[length-remainingSize];
for(int i=remainingSize;i>1;i--)
{
array[length-i]=array[length-i+1];
}
array[length-1]=firstLeft;
}
}
输出结果:1234 1243 1342 1324 1423 1432 2341 2314 2413 2431 2134 2143 3412 3421 3124 3142 3241 3214 4123 4132 4231 4213 4312 4321
写完后上网一搜全排列,又发现了一些关于这个问题的进一步说明,有多种算法可实现,包括迭代的算法,有兴趣的童鞋可以上网搜一下,了解了解。