Unique Paths
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.
动态规划,很经典的问题。
转移方程dp[i][j] = dp[i – 1][j] + dp[i][j – 1];
说明几点:
1. 构造动态规划矩阵map时,长宽分别取m+1, n+1。并把第一行和第一列置0;map[1][1]=1.这样可以避免进行边界检查。
2. 遍历矩阵从1,1开始,但跳过1,1.
class Solution { public: int uniquePaths(int m, int n) { int map[m+1][n+1]; for(int i = 0; i < m + 1; i++){ map[i][0] = 0; } for(int i = 0; i < n + 1; i++){ map[0][i] = 0; } map[1][1] = 1; for(int i = 1; i < m + 1; i++){ for(int j = 1; j < n + 1; j++){ if(i == 1 && j == 1) continue; map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m][n]; } };