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

Java实现泛型全排列

2014-06-27 15:36 211 查看
全排列是经常在面试中遇到的编程题,对于才工作的人来说,有时候还是比较恼火的,废话不多数哈,下面来看下泛型的全排列

package Test;

public class Test03 {
public static void main(String[] args) {
String[] ch = {"a","b","c"};
per(ch);
}

private static<T> void per(T[] ch){
doPer(ch,0,ch.length);
//		swap(ch,0,ch.length);
}

private static<T> void doPer(T[] ch, int first, int num){
if(num > 1){
for(int i = first;i < first + num;i++){
swap(ch, first, i);
doPer(ch,first + 1,num -1);
}
}else{
print(ch);
}
}

private static<T> void swap(T[] x,int index1,int index2){
T temp = x[index1];
x[index1] = x[index2];
x[index2] = temp;
}

private static<T> void print(T[] ch){
for(T t:ch){
System.out.print(t+" ");
}
System.out.println();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: