题目:
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?
题意:机器人从左上角作为起点前往右下角的重点,每次只能往右移或者往下移。
思路:对于每个格点我们考虑机器人能够从哪些格点跳到该格点上。比如对于(0,1)这个位置即第一行第二列的位置,也就是机器人的起始位置的右一个位置,(0,1)只能由(0,0)往右跳一格到达,而对于(2,2)可以由(1,2)或者(2,1)跳达。第一行的格点只能由机器人往右跳到达,第一列的格点只能由机器人往下跳一格到达,其余的格点可以由机器人从左往右跳一格或者从上往下跳一格到达。思路到这儿就很明显了,这是一个动态规划的问题。
- DP[i][j] = 1(i == 0 || j == 0);
- DP[i][j] = DP[i-1][j] + DP[i][j-1];
参考以下代码:
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1)return 0;
int **DP = new int*[m];
for(int i = 0; i < m; i++){
DP[i] = new int[n];
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 || j == 0)DP[i][j] = 1;
else DP[i][j] = DP[i-1][j] + DP[i][j-1];
}
}
return DP[m-1][n-1];
}
};