Dynamic Programming - 62. Unique Paths

2020-09-23 17:19:30 浏览数 (3)

62. 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 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

思路:

题目意思是从一个m x n 的矩阵的左上方走到右下方 ,只能向下或者向右走,一共有多少种走法。同样,先看这个问题的最后一步,最后一步是走到第m行n列这个格子,问有多少种走法,那这个格子只能是从第m-1行第n列往下走一步或者第m行第n-1列往右走一步,由加法原则就可以知道,到达m行n列是这两种走法的和。所以就变成了得知道m行n-1列和m-1列n行的走法,这就是子问题,状态转移方程就是dp[i][j]=dp[i-1][j] dp[i][j-1],dp[i][j]代表了走到第i行第j列的走法。然后考虑初始条件和边界条件,dp[0][j]和dp[i][0]不能通过状态转移方程求出,所以这两个就是初始条件。 (可以在维度上优化为一维,状态转移方程变成dp[i] = dp[i-1] dp[i],从左往右扫或者从上往下扫。以从上往下扫为例,当前dp[i]代表的就变成了走到dp[i]需要从左边往右走一步,也就时dp[i-1],和上一层的第i列那个格子往下走一步,也就是上一个dp[i])

代码:

go:

代码语言:javascript复制
/*func uniquePaths(m int, n int) int {

    if m <= 0 || n <= 0 {return 0}
    
    // initial dp array
    dp := make([][]int, m)
    for i := 0; i < len(dp); i   {
        dp[i] = make([]int, n)
    }
    
    // find unique path
    for i := 0; i < m; i   {
        for j := 0; j < n; j   {
            if i == 0 || j == 0 { // initialization
                dp[i][j] = 1
            } else {
                dp[i][j] = dp[i][j-1]   dp[i-1][j] 
            }
        }
    }
    
    return dp[m-1][n-1]
}*/

func uniquePaths(m int, n int) int {
    if m <= 0 || n <= 0  {
        return 0
    }
    
    dp := make([]int, n)
    
    // find unique path
    for i := 0; i < m; i   {
        for j := 0; j < n; j   {
           if j == 0 {  // initialization
              dp[j] = 1
           } else {
              dp[j] = dp[j]   dp[j-1]    
           }
        } 
    }
    
    return dp[n-1]
}```

1 人点赞