(DP 线性DP 递推) leetcode 62. Unique Paths

mac2022-06-30  108

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 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

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

----------------------------------------------------------------------------------------------

我觉得这个是一个线性DP题,只不过是二维而已,这个DP的状态转换式比较好找,由于是只有向右和向下两个方向,所以,可以用dp[i][j]  = dp[i-1][j] + dp[i][j-1]得到,其中,dp[i][j]表示的是到这个(i,j)坐标中机器人所经过的总路线,而dp[i-1][j]表示的是机器人到(i-1,j)这个坐标中已经经过的总路线,同理,dp[i][j-1]也可以这么理解的。dp[i][j]就是把这两个得到的总路线相加起来。不过要注意的就是要先初始化。

C++代码:

class Solution { public: int uniquePaths(int m, int n) { int dp[m][n]; memset(dp,0,sizeof(dp)); 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]; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10842571.html

最新回复(0)