唯一路径

版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club/ 欢迎来踩~~~~ https://blog.csdn.net/w7239/article/details/84991742

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.

题目大意

在一个m*n的表格中,从左上角的起点处走到右下角的终点处共有多少条不同的路径。
在本题中,上图中的表格是3*7的一个表格,有多少种不同的路径。

思路

动态规划思想

这是一个典型的入门级动态规划问题,很容易想到动态规划的思路。

二维数组动态规划

把问题中的m*n的表格翻译成m*n的二维数组,原理是除了第一行或者第一列的格子外,到其他格子路径的走法是:每一个格子的可到达路径数=左边一个格子的可到达路径数+上边一个格子的可到达路径数(第一行或者第一列的格子到达的路径数均为1)。时间复杂度为O(N^2), 空间复杂度为O(N^2)

一维数组动态规划

用一维数组代替二维数组,动态更新。时间复杂度为O(N^2),空间复杂度为O(N)

组合数学思想

组合数学的思想是,从左上角的起点处走到右下角的终点处,只能向右走或者只能向下走,从行上看走过了m - 1行,从列上看走过了n - 1列,即可以理解为排列组合的问题,所以一共需要的步数中挑出m - 1个向下走,剩下的n - 1个就是向右走,其实就是从(m-1+n-1)里挑选(n-1)或者(m-1)个,即:C(n,r),其中n = (m-1+n-1)r = (n-1)或者r = (m-1),公式为:n! / ( r! * (n - r)! )

代码

动态规划(二维数组)

int uniquePaths(int m, int n) {
    // 用vector定义int类型的二维数组,并全部初始化为1
    vector<vector<int > > dp(m, vector<int >(n, 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];
        }//for
    }//for
    return dp[m-1][n-1];
}

动态规划(一维数组)

int uniquePaths(int m, int n) {
    // 用vector定义int类型的一维数组,并全部初始化为1
    vector<int > dp(n, 1);
    for(int i=1; i<m; i++)
    {
        for(int j=1; j<n; j++)
        {
            // 用一维数组模拟二维数组,动态更新当前行
            dp[j] += dp[j-1];
        }//for
    }//for
    return dp[n-1];
}

组合数学(排列组合)

int uniquePaths(int m, int n) 
{
    long x = m+n-2;// 不用 long 会溢出,阶乘求出来太大了
    long y = min(m,n)-1;
    long up = 1,down =1;// 最后求组合数的分子 / 分母
    // if(m==1||n==1) return 1;
    for(int i = 0;i<y ;i++)
    {
        up *= x--;
    }
    for(int i = y; i>0; i--)
    {
        down *= i;
    }
    return int(up/down);
}

以上。


版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


猜你喜欢

转载自blog.csdn.net/w7239/article/details/84991742