1

在我的 compsci UIL 类中存在一个挑战问题,即使用尾递归来获取给定数字的二项式系数列表。我想我已经很接近了,但我在基本情况下遇到了困难。

以下是我的代码:

 public static Cons binomial(int n) 
    {
        return binomialb(n, null, 1);

    }
public static Cons binomialb(int n, Cons last, int power)
{

    if(n == power || n < 0)
    {
        return cons(1, null);
    }   
    else if(last == null)
    {
        last = cons(1, cons(1, null));
        return binomialb(n-1, last, power);
    }
    else
    { 
        Cons lst = cons(1, null);
        while(rest(last)!=null)
        {
        lst = cons((Integer)first(last)+(Integer)first(rest(last)), lst);
            last = rest(last);
        }
        return binomialb(n-1,lst,power);
    }

}

现在我只是得到一个列表(1).....

4

1 回答 1

0

你的递归调用总是binomialb(n-1,something,power),所以唯一改变的是第一个参数,n和列表。你最初的电话有power = 1,所以这将永远如此。现在你的第一个条件是

if (n == power || n < 0) { 
    return cons(1,null);
}

如果您n > 1最初调用它,调用将变为binomialb(n-k,...,1)for k = 1, ..., n-1。最后,电话binomialb(1,lotsOfWastedWork,1)将愉快地返回cons(1,null)。如果您最初使用 调用它n < 1n < 0将使其在最多一次递归调用后返回相同,n = 1立即返回cons(1,null)

无论何时last在调用中不为空,您都应该使用它。

于 2012-02-04T16:00:15.737 回答