还拿斐波那契函数举例:
递归:
int fib(int n){ if(n>1) return fib(n-1) + fib(n-2); else return n; // n = 0, 1时给出recursion终止条件 }
而动态规划:
F[0] = 0;F[1] = 1; for(i = 2; i <= N; i++) F[i] = F[i-1] + F[i-2];
看完,是不是觉得和迭代很像?没错
这里,动态规划和迭代在实现上是一样的。(其他地方可能就不一样。。)
。总结:能用动态规划或者迭代,就不用递归,因为递归太耗堆栈了。效率不高。