1、题目:
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?
Example 1:
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28
2、解答: f(n,m)只能从上或者左边走过来,因此f(n,m) = f(n-1,m) + f(n,m-1)。现在看起始条件,若n = 0 ,f(0,m) = 1,m=0,f(n,0) = 1
3、代码:
C++代码
class Solution { public: int uniquePaths(int m, int n) { int path[m][n]; for(int i=0;i<m;i++) path[i][0] = 1; for(int j=0;j<n;j++) path[0][j] = 1; for(int i=1;i<m;i++) for(int j=1;j<n;j++) path[i][j] = path[i-1][j] + path[i][j-1]; return path[m-1][n-1]; } };
python代码
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ path = [[1 for i in range(n)] for j in range(m)] for i in range(1,m): for j in range(1,n): path[i][j] = path[i-1][j] + path[i][j-1] return path[-1][-1]