Java递归时报错:java.lang.StackOverflowError,求解

干饭人之路 CSDN会员 干饭人之路 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
/**
* xxx 20181018
* 从整形ArrayList source中 抽取n个元素,所构成的组合为 ArrayList<ArrayList<Integer>> result
* @param ArrayList<Integer> source
* @param int n
* @return ArrayList<ArrayList<Integer>> result
*/

public static ArrayList<ArrayList<Integer>> CombinationT(ArrayList<Integer> source,int n)
{ System.out.println("CombinationT(source,n):source.size()="+source.size()+"; n="+n);
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if(n==1)
{
for(int i=0;i<source.size();i++)
{ Object t=source.get(i);
ArrayList a= new ArrayList();
a.add(t);
result.add(a);
}
}
else if(source.size()==n)
{
result.add(source);
}
else
{
ArrayList<Integer> psource=new ArrayList<Integer>();
//[source.size()-1];
for(int i=0;i<source.size()-1;i++)
{
psource.add(source.get(i));
}
//报错信息所提示的84行代码
result.addAll(CombinationT(psource,n));
ArrayList<ArrayList<Integer>> tmp=CombinationT(psource,n-1);
for(int i=0;i<tmp.size();i++)
{
ArrayList<Integer> rs=new ArrayList<Integer>();
for(int j=0;j<n-1;j++)
{
rs.add(tmp.get(i).get(j));
}
rs.add(source.get(source.size()-1));
result.add(rs);
}
}
return result;
}


上面这个java写的组合方法在多次递归调用CombinationT后出现:
Exception in thread "main" java.lang.StackOverflowError
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
at com.fh.xt.utils.Combination.CombinationT(Combination.java:84)
...
的栈溢出报错,如何修改才能避免栈溢出???
...全文
评论 6
收藏 已收藏
分享
返回顶部
干饭人之路 CSDN会员
Java SE 62,621 成员 307,251 内容