排列算法

阿拉希神猪 2012-03-29 11:03:15
无聊看了个面试题,考排列算法的。要求十分钟内答出,我搞了一两个小时,只搞出了个排列算法。

只是记得高中学的排列算法的计算方式就是n*(n-1)*(n-2)*(n-3)... , 然后模拟这个写了个算法。

假设1、2、3 排列
第一遍,生成 数组:1、2、3
第二遍,数组变成:12、13、21、23、31、32
第三遍,数组变成:123、132、213、231、312、321

原理就是,
第一个位置,有3钟方法。 然后搞出三个数。
第二个位置,有2钟方法。然后在第一个的基础上搞出3*2个数。
...


求各种板砖,因为我这算法完全没有效率!


package com;

import java.util.ArrayList;
import java.util.List;

public class Test {

public static String[] globalSt = {"1","2","3"};
public static List<String> tempList = new ArrayList<String>();
public static List<String> resulList = new ArrayList<String>();

public static void main(String[] args) {
for(int u=0;u<globalSt.length;u++){
resulList.add(globalSt[u]);
}
round(globalSt.length);
System.out.println("============");
for(int i=0;i<resulList.size();i++){
System.out.println(resulList.get(i));
}

}

public static void round(int iRound){
if(iRound == 1)
return ;
tempList = new ArrayList<String>();
for(int i=0; i<resulList.size(); i++){
String st = resulList.get(i);
for(int j=0;j<globalSt.length;j++){ //只要没出现过的,都可以放进去
if(st.indexOf(globalSt[j])<0){//没有
String newSt = st + globalSt[j];
tempList.add(newSt);
}
}
}

resulList = tempList;
for(int i=0;i<resulList.size();i++){
System.out.println(resulList.get(i));
}
round( iRound -1);

}

}


...全文
65 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

25,980

社区成员

发帖
与我相关
我的任务
社区描述
高性能WEB开发
社区管理员
  • 高性能WEB开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧