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?

题目开始可以尝试使用简单的递归,发现超时
后来尝试使用动态规划的算法,最后p[m][n]的步数取决于前面p[m-1][n]和p[m][n-1]的大小,当m=0或者n=0时,也就是只有一行或者一列,那么前面只有一种走法。

class Solution {
public:
    int uniquePaths(int m, int n) {
      int p[m][n];

        for(int i = 0;i<m;i++) {
            for(int j = 0;j<n;j++) {
                if(i==0||j==0){
                    p[i][j] = 1;
                }
                else
                p[i][j] = p [i-1][j] + p[i][j-1];
            }
        }
        return p[m-1][n-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值