有没有办法在不使用堆栈的情况下将这种递归算法转换为迭代算法?
public static float T1(int n, float y) {
if (n == 0)
return y;
if (n == 1)
return 1;
return 2 * y * T1(n - 1, y) - T1(n - 2, y);
}
让我感到困惑的是递归内部有两个调用,而且我不知道如何使用循环进行转换。
最佳答案
这是一种使用 for
循环进行相同计算的方法。
public static float T1(int n, float y) {
if (n==0) return y;
if (n==1) return 1;
float p1 = 1, p2 = y; // track the previous two values
for (int i=2; i <= n; ++i) {
float p = 2*y*p1 - p2; // calculate the result for this iteration
p2 = p1; // update the previous values to be used in the next iteration
p1 = p;
}
return p1;
}
关于java - 转换递归函数并更多地调用迭代函数java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239709/