题目:
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
题目分析:
题目意思是给定一个m*n的表格,然后只能向右和向下走,问有多少条路径从左上角到右下角
使用动态规划的思路
考虑我们现在要到达坐标为x,y的方格,到达这个方格的上一步只有两种,一种是从左边的一个方格来,一种是从上边的一个方格来,这两种情况各有一条路径到达这个方格,因此到达这个方格的路径数就是到达这两个方格的路径数*1再相加,而如果x==1或者y==1无论另一个变量为多少这时候都只有一条路径能到达,这个是边界条件
因此动态规划方程为dp[x][y] = dp[x-1][y] + dp[x][y-1]
c++代码:
class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 0 || n == 0) return 1;
if (m == 1 || n == 1) return 1;
int** dp = new int*[m];
for (int i = 0; i < m; i++) {
dp[i] = new int[n];
}
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};