A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
1 2 3
Above is a 3 x 7 grid. How many possible unique paths are there?
publicintuniquePaths(int m, int n) { return uniquePaths(1,1,m, n); }
publicintuniquePaths(int currentRow, int currentColumn, int m, int n){ if(currentRow==m || currentColumn==n){ return1; } return uniquePaths(currentRow+1, currentColumn, m ,n ) + uniquePaths(currentRow, currentColumn+1, m, n); }
同样的思路,也可以从终点开始往回计算,如果能够到达起点,则返回1,否则返回0。
1 2 3 4 5 6
publicintuniquePaths2(int m, int n){ if(m==1 || n==1){ return1; } return uniquePaths2(n-1, m) + uniquePaths2(n, m-1); }