全排列算法——递归版

今天在阅读《Java数据结构与算法 第二版》的时候,看到了一个关于全排列的问题。给出的例子是如何排列出 字母c,a,t所有的不同组合。我按照递归的思路写了一下,成功运行。大致思路是,固定第一个元素,把剩余的全排列,然后数组向左轮转(最左边的转到最右边)然后重复这个过程直到数组中的每一个元素都出现在了第一的位置。

下面是代码:
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
写完后上网一搜全排列,又发现了一些关于这个问题的进一步说明,有多种算法可实现,包括迭代的算法,有兴趣的童鞋可以上网搜一下,了解了解。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值