循环递归求数组里数据的组合
来源:互联网 发布:全键编程什么意思 编辑:程序博客网 时间:2024/05/23 23:44
代码:
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,这样就可以取得不同的数据。
- 循环递归求数组里数据的组合
- 求 数组里 和为s的所有组合
- 我的Java开发学习之旅------>使用循环递归算法把数组里数据数组合全部列出
- 求组合数的递归算法
- 求数组里相同数据个数
- 求数组里相同数据个数
- ////////////////递归求组合算法//////////////
- 递归求组合
- 递归 求组合
- 递归求组合数
- 递归求组合
- 列出数组里的数的组合
- for循环里的递归,和双重递归
- 《循环非递归_递归_求 n! 的值》
- 求数组中任意个数的组合
- PHP求给定数组的组合
- 数组组合的递归与非递归实现
- 求数组(List)组合
- LoadRunner_ function_持续更新
- The sequence of the learning ORACLE.
- 成就Google的Page Rank技术
- Cookie跨域和跨应用的问题
- JS 前端验证 脚本
- 循环递归求数组里数据的组合
- locale
- 数据库损坏修复!!
- .net获取当前时间的方法示例
- 设计快速跨平台SIMD矢量库
- 管理 对人不对事
- 使用动态包导出函数的调用单元完整源代码
- apache性能优化
- 9500如何调查通话记录