Topic: 请帮忙看看一个递归算法

  Print this page

1.请帮忙看看一个递归算法 Copy to clipboard
Posted by: surroad
Posted on: 2008-12-14 00:31

用递归算法,有个问题,nums较大时(在我的机器>25)会java.lang.OutOfMemoryError: Java heap space,不知算法有问题还是内存已经超过jvm系统限制的原因?

public class Combination {

public static void main(String[] args) {
Combination t = new Combination();

// t.getAllArray(list, 0);
for(int i=1;i<7;i++) {
int ar[]={i};
t.arr.add(ar);
}

t.allcombination(3, 6,t.arr);

}

List arr= new ArrayList();
int dept = 0;
int counter=0;
List comb =new ArrayList();
public void allcombination(int nums, int size,List list) {

List combtmp =new ArrayList();
nums–;
if (nums == 0) {
// nums = nums_c;
return;
}

for(int j=0;j<list.size();j++){
int curlist[] =(int[])list.get(j);
// int tmp[][] = new int[arr.size()][number];
int startidx = curlist[curlist.length-1];
// System.out.println(”startidx:”+startidx+” length:”+curlist.length);
for (int i =startidx; i <= size; i++) {
int [] s3 = new int[curlist.length+1];//s3必须先初始化分配空间
System.arraycopy(curlist,0,s3,0,curlist.length);

s3[curlist.length] = i;
combtmp.add(s3);
// printArray(s3);
counter++;
}
}

// System.out.println(”=================”);
if(nums==1){
System.out.println(”——–”+counter+” “+nums);
printListArr(combtmp);
}
allcombination(nums, size,combtmp);

}

static void printListArr(List list){
for(int i=0;i<list.size();i++){
printArray((int[])list.get(i));
}
}
public static void printArray(int [] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+” “);
}
System.out.println();
}

}

2.Re:请帮忙看看一个递归算法 [Re: surroad] Copy to clipboard
Posted by: wangyu336
Posted on: 2008-12-15 12:38

至于你写的东西,我不想看,你就告诉我想实现什么就可以了?我可以根据你要做的东西来指导你,把正确的思路告诉你,然后再去尝试!对于很多初学者甚至中级的程序员来说,都会因为思路不清晰,导致简单东西复杂划!

3.Re:请帮忙看看一个递归算法 [Re: surroad] Copy to clipboard
Posted by: micsolaris
Posted on: 2008-12-15 23:00

呵呵,那天我也仔细的看了下代码,也测试了。但是后来感觉很凌乱所以…………
看来代码是自己写的会比较清晰啊~~

4.Re:请帮忙看看一个递归算法 [Re: surroad] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2008-12-26 23:38

surroad, there are at least 2 people here to help you.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923