代码:
import java.util.*;
import java.io.*;
/*
* 把一个数组里的数组合全部列出,比如{1,2}列出来为1,2,12,21.
*/
public class Test_recursion {
static List temp=null;
public static void main(String[] args)throws Exception {
String[] array=new String[]{"1","2","3"};
long time1=System.currentTimeMillis();
System.out.println("time1:"+time1);
listAll(Arrays.asList(array), "");
long time2=System.currentTimeMillis();
System.out.println("time1:"+time2);
System.out.println("耗时为(秒):"+(time2-time1)/1000.0);
import java.io.*;
/*
* 把一个数组里的数组合全部列出,比如{1,2}列出来为1,2,12,21.
*/
public class Test_recursion {
static List temp=null;
public static void main(String[] args)throws Exception {
String[] array=new String[]{"1","2","3"};
long time1=System.currentTimeMillis();
System.out.println("time1:"+time1);
listAll(Arrays.asList(array), "");
long time2=System.currentTimeMillis();
System.out.println("time1:"+time2);
System.out.println("耗时为(秒):"+(time2-time1)/1000.0);
}
public static void listAll(List candidate,String prefix){
if(!prefix.equals("")){
System.out.println(prefix);
}
for (int i = 0; i < candidate.size(); i++) {
temp=new LinkedList(candidate);//转换为LinkedList便于安插和移动
listAll(temp, prefix+temp.remove(i));
}
}
public static void listAll(List candidate,String prefix){
if(!prefix.equals("")){
System.out.println(prefix);
}
for (int i = 0; i < candidate.size(); i++) {
temp=new LinkedList(candidate);//转换为LinkedList便于安插和移动
listAll(temp, prefix+temp.remove(i));
}
}
}
结果:
time1:1190726257250
1
12
123
13
132
2
21
213
23
231
3
31
312
32
321
time1:1190726257250
耗时为(秒):0.0
1
12
123
13
132
2
21
213
23
231
3
31
312
32
321
time1:1190726257250
耗时为(秒):0.0
总结:
这题用到了java.util中的集合LinkedList(为链表结构,便于删除和移动元素),应用Arrays.asList把array转换为list。
使用循环递归调用listAll,内部用LinkedList的remove方法产生不同的LinkedList,这样就可以取得不同的数据。