簡體   English   中英

遞歸方法中的java.lang.StackOverflowError

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM