当前位置:网站首页>力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
2022-07-07 01:41:00 【裴南苇_】
今天遇到一道个人认为很有价值的动态规划问题。从这道题里,个人感觉对动态规划有了更深刻的了解,大家可以看看对自己又没有帮助。
先看题目:
一个机器人位于一个 m x n 网格的左上角,机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角问总共有多少条不同的路径?
示例
输入:m = 3, n = 2
输出:3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右
3. 向下 -> 向右 -> 向下
解答:
由题目得知,每一次只能向下或者向右移动
由此我们推知 ===》 到达一个格子的路径数量,由它左边格子和上边格子所决定
由此我们推知 ===》 这里可以使用动态规划的思想来解决
由此动态方程 ===》 dp[i][j] = dp[i-1][j] + dp[i][j-1]
至此,我们已经解决一半的问题了,然后我们再思考第一列和第一行,由于每一次只能向下或者向右移动,所以第一行的每个格子都只能由它左边的格子向右移动而来, 所以第一行dp[0][j] 都应该为1,第一列格子同理。
至此分析结束,列出代码
public int uniquePaths(int m, int n) {
int[][] dp = new int [m][n];
for(int i=0;i<n;i++){
dp[0][i] = 1;
}
for(int i=0;i<m;i++){
dp[i][0] = 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];
}

好了,这次的文章就到这里,喜欢的同学可以点赞收藏,遇到问题,可以评论,或者留言,我一定会第一时间给到回馈,感谢观看!!
注:本文为本人学习时心得分享,有讲错或者需要改正的地方,请指正,我会虚心接受
边栏推荐
- 693. Travel sequencing
- Financial risk control practice - decision tree rule mining template
- Three updates to build applications for different types of devices | 2022 i/o key review
- 安装VMmare时候提示hyper-v / device defender 侧通道安全性
- Storage of dental stem cells (to be continued)
- Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)
- 3531. 哈夫曼树
- 深度聚类:将深度表示学习和聚类联合优化
- 3428. Put apples
- Markdown displays pictures side by side
猜你喜欢
![[FPGA] EEPROM based on I2C](/img/28/f4f2efda4b5feb973c9cf07d9d908f.jpg)
[FPGA] EEPROM based on I2C

Markdown 并排显示图片

Jstack of JVM command: print thread snapshots in JVM

Three updates to build applications for different types of devices | 2022 i/o key review

Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)

从“跑分神器”到数据平台,鲁大师开启演进之路

外设驱动库开发笔记43:GPIO模拟SPI驱动

JMeter's own functions are not enough? Why don't you develop one yourself

rt-thread 中对 hardfault 的处理

Developers don't miss it! Oar hacker marathon phase III chain oar track registration opens
随机推荐
vim映射大K
Implementation of VGA protocol based on FPGA
cf:C. Column Swapping【排序 + 模拟】
Career experience feedback to novice programmers
laravel 使用腾讯云 COS5全教程
The boss always asks me about my progress. Don't you trust me? (what do you think)
A freshman's summary of an ordinary student [I don't know whether we are stupid or crazy, but I know to run forward all the way]
[Shell]常用shell命令及测试判断语句总结
Redisl garbled code and expiration time configuration
牛客小白月赛52 E.分组求对数和(二分&容斥)
进程间通信之共享内存
693. 行程排序
为不同类型设备构建应用的三大更新 | 2022 I/O 重点回顾
Detailed explanation of platform device driver architecture in driver development
Solve pod install error: FFI is an incompatible architecture
Storage of dental stem cells (to be continued)
"Parse" focalloss to solve the problem of data imbalance
Talking about reading excel with POI
[FPGA tutorial case 14] design and implementation of FIR filter based on vivado core
Jmeter自带函数不够用?不如自己动手开发一个