有没有办法在不使用堆栈的情况下将此递归算法转换为迭代?
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);
}
令我困惑的是在递归中有两个调用,我不知道如何使用循环转换它。
答案 0 :(得分:2)
这是一种使用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;
}