返回numberOfPaths(m-1,n)+ numberOfPaths(m,n-1)调用的第二次递归是如何工作的?
#include <iostream>
using namespace std;
// Returns count of possible paths to reach cell at row number m and column
// number n from the topmost leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
// If either given row number is first or given column number is first
if (m == 1 || n == 1)
return 1;
// If diagonal movements are allowed then the last addition
// is required.
return numberOfPaths(m-1, n) + numberOfPaths(m, n-1);
// + numberOfPaths(m-1,n-1);
}
int main()
{
cout << numberOfPaths(3, 3);
return 0;
}
答案 0 :(得分:0)
它再次调用函数numberOfPaths
。使用m-1
和n
,使用m
和n-1
一次,然后添加结果。
如果您致电numberOfPaths(2,2)
,则会致电numberOfPaths(1,2)
和numberOfPaths(2,1)
,这两个回复1
,numberOfPaths(2,2)
将返回2
。