【发布时间】:2016-05-13 22:45:22
【问题描述】:
我目前正在研究一种算法,以输出具有 n 个整数序列的所有排列,并且该函数在 6 个元素之前都可以正常工作,但是当它超过 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 个元素的数组。是否有任何具有相同方法签名的伪代码,或者有什么方法可以调整堆栈跟踪,因为这应该可以部分解决问题?
【问题讨论】:
-
请添加导致错误的代码
-
您对正在发生的事情的假设与现实不符。在调试器中浏览一下代码,看看为什么会这样。更好的是,开始编写 Junit 测试来锻炼课程并增加复杂性。
-
调用堆栈溢出时会发生堆栈溢出,这是由有限数量的调用引起的,而不是无限数量的调用。
-
如果你的堆栈大小超过了递归调用的数量,你会得到一个
StackOverflowException。确切的堆栈大小取决于 JVM 及其设置,因此我们无法告诉您什么递归深度太大。如果您的代码没有执行任何不必要的递归(使用调试器检查)并且您仍然遇到堆栈溢出,那么请减少您的问题大小或将您的算法重写为非递归版本。 -
当我编写不执行停止条件的递归方法时,总是会出现堆栈溢出。保证你的有缺陷。
标签: java recursion permutation