我不明白为什么这是向前递归:
int count(int x) {
if(x<=0) return 0;
return 1 + count(x - 1);
}
这是一道实践考试中的问题,答案是它是正向递归。为什么会是这样呢?我应该如何区分这两种情况呢?
int count(int x) {
if(x<=0) return 0;
return 1 + count(x - 1);
}
这是一道实践考试中的问题,答案是它是正向递归。为什么会是这样呢?我应该如何区分这两种情况呢?
int count(int x, int res) {
if(x<=0) return res;
return count(x - 1, res + 1);
}
注意我们什么也不做。
1 + result_of_recursion
,而不是递归本身。 - extraneon你看过这个stackoverflow问题,尾递归和正向递归的区别吗?
Matthew已经回答了,简要概括一下:
int count(int x) {
if(x<=0) return 0;
return 1 + count(x - 1);
}
int count(int x) {
if(x<=0) return 0;
int tmp_result = count(x - 1);
return 1 + tmp_result; // e.g. recursion is not last
}