递归方法中的java.lang.StackOverflowError

时间:2016-05-13 12:27:05

标签: java recursion permutation

我目前正在研究一种算法,用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个元素的数组。是否存在具有相同方法签名的伪代码,或者是否有任何方法可以调整堆栈跟踪,因为这应该部分解决问题?

1 个答案:

答案 0 :(得分:3)

你的代码不会错过return语句吗?为什么你打电话给isPermutated而不用担心重新计算的价值呢?

您的代码永远不会返回true。