[英]java.lang.StackOverflowError in a recursive method
我目前正在研究一种算法,该算法可以输出具有n个整数的序列的所有排列,并且该函数在6个元素之前都可以正常工作,但是当它超过该数量时,我得到了StackOverflowError消息。 我已经阅读了有关此主题的一些问题,但是我发现,当递归方法具有无限数量的调用并且在其基本情况执行时似乎并非如此,就会发生这种情况。
//int[] c parameter receives an array with n elemens to permute
//int i represents the length of the sequence to permute (ai,...,aN)
public boolean isPermutated(int[] c, int i)
{
int max = 0; // the maximum number from a sequence (a1,...,aN) and
int index = 0; // the index where the maximum is
int lessThan; // an index preceded by maximum
//Base case
if(i == 1)
{
return false;
}
// Gives the Maximum element from a sequence (ai,...,aN)
for(int count = c.length - i; count < c.length; count++)
{
if(max < c[count])
{
max = c[count];
index = count;
}
}
// Swap the Maximum from index to index-1
if(max != c[c.length - i])
{
lessThan = c[index-1];
c[index-1] = max;
c[index] = lessThan;
//move each maximum from a sequence (a,...,aN) to the last index ex, (3,2,1)->(2,1,3)
if(i != c.length)
{
while((i-c.length) != 0)
{
for(int count = c.length - (i+1); count < c.length-1; count++)
{
int before;
int after;
before = c[count];
after = c[count+1];
c[count] = after;
c[count+1] = before;
}
i++;
}
}
// print array c elements
for(int e:c)
System.out.print(e);
System.out.println();
isPermutated(c, c.length);
}
else
{
i--;
isPermutated(c, i);
}
return true;
}
我很沮丧,因为我需要10个元素组成的数组。 是否有具有相同方法签名的伪代码,或者有任何方法可以调整堆栈跟踪,因为这应该可以部分解决问题?
您的代码不会错过return语句吗? 为什么在不担心转换值的情况下调用isPermutated?
您的代码永远不会返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.