Leetcode(62)Unique Paths

本文介绍了一种使用动态规划和组合数学解决机器人从网格左上角移动到右下角的不同路径数量的方法。通过分析,提供了两种解决方案:一种是利用动态规划递推公式;另一种则是直接计算组合数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:从左上角到右下角,只能往右走或者往下走,有多少种不同的走法。

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?


分析:动态规划,设f[i][j]表示从点(i,j)到终点有多少种不同的走法。那么f[i][j]=f[i+1][j]+f[i][j+1].

           边界条件:f[m-1][n-1]=1

           方向:从向往上,从右往左

           复杂度:O(n²)。

           用动态规划很慢呀,其实这道题可以直接计算。因为每种走法有m-1次向右,n-1次向下,所以其实就是从m+n-2次移动中选择m-1次为向右移,其他位向左移。

          所以答案是C(m+n-2,m-1)。

代码(动态规划):

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m==0||n==0) return 0;
        if(m==1||n==1) return 1;
        vector<vector<int> > f(m,vector<int>(n, 0));
        f[m-1][n-1]=1;
        
        for(int j=n-1;j>=0;j--)
         for(int i=m-1;i>=0;i--)
         {
             if(i+1<m) f[i][j]+=f[i+1][j];
             if(j+1<n) f[i][j]+=f[i][j+1];
         }
         return f[0][0];
    }
};
排列组合:

class Solution {
public:
    int uniquePaths(int m, int n) {
         double res=1;
         int N=m+n-2;
         int k=1;
         while(k<=n-1)
         {
             res=res*(N-(n-1)+k)/k;
             k++;
         }
         return (int)res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值