zoukankan      html  css  js  c++  java
  • (DP 线性DP 递推) leetcode 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

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

    我觉得这个是一个线性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];
        }
    };
  • 相关阅读:
    jQuery入门级part.2
    jQuery入门级part.1
    总结十二天
    延时器和定时器
    总结第十一天
    总结第十天
    总结第九天
    android特殊字符
    android 查看 当前activity
    京东运营 不错的帖子
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10842571.html
Copyright © 2011-2022 走看看