返回numberOfPaths(m-1,n)+ numberOfPaths(m,n-1)调用的第二次递归如何工作?

时间:2016-03-01 16:45:00

标签: recursion

返回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;
}

1 个答案:

答案 0 :(得分:0)

它再次调用函数numberOfPaths。使用m-1n,使用mn-1一次,然后添加结果。

如果您致电numberOfPaths(2,2),则会致电numberOfPaths(1,2)numberOfPaths(2,1),这两个回复1numberOfPaths(2,2)将返回2