Leetcode P0062"Unique Paths" 题解

2020/08/28 Leetcode

博文中会简要介绍Leetcode P0062题目分析及解题思路。

“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?

这道题的思路很直接明了。递推式如下:

    令dp[i][j]表示到第i行第j列的位置所有不同的路径走法

    dp[i][0] = 1
    dp[0][j] = 1
    边界只有一条路

    dp[i][j] = dp[i-1][j]+dp[i][j-1]
    任何一个位置等于来自上面的走法和来自左边的走法之和。

以下是Java的题解代码实现。

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for (int itr=0; itr<m; ++itr)
            dp[itr][0] = 1;
        for (int itr=0; itr<n; ++itr)
            dp[0][itr] = 1;
        
        for (int i1=1; i1<m; ++i1) {
            for (int j2=1; j2<n; ++j2) {
                dp[i1][j2] = dp[i1-1][j2]+dp[i1][j2-1];
            }
        }
        
        return dp[m-1][n-1];
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> dp(m, vector<int>(n, 1));
        
        for (int i1=1; i1<m; ++i1) {
            for (int j2=1; j2<n; ++j2) {
                dp[i1][j2] = dp[i1-1][j2]+dp[i1][j2-1];
            }
        }
        
        return dp[m-1][n-1];
    }
};

Search

    Table of Contents