当前位置:网站首页>力扣:62.不同路径
力扣:62.不同路径
2022-08-04 05:14:00 【empty__barrel】
力扣:62.不同路径
题目:
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。
问总共有多少条不同的路径?
代码:dp一题比代码随想录空间利用率高
class Solution {
public:
int uniquePaths(int m, int n) {
int dp[m][n];
// dp[0][0] = 0;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(i== 0 && j==0) {
dp[0][0] = 1;
continue;
}
int a = j-1 < 0? 0:dp[i][j-1];
int b = i-1 < 0? 0:dp[i-1][j];
dp[i][j] = a+b;
}
}
return dp[m-1][n-1];
}
};
代码随想录代码:
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 0));
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];
}
};
代码:一维数组的实现
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> dp(n);
for (int i = 0; i < n; i++) dp[i] = 1;
for (int j = 1; j < m; j++) {
for (int i = 1; i < n; i++) {
dp[i] += dp[i - 1];
}
}
return dp[n - 1];
}
};
代码:数论方法
无论怎么走,走到终点都需要 m + n - 2 步,在这m + n - 2 步中,一定有 m - 1 步是要向下走的,此时就是一个组合问题了,判断m-1步是哪几步即可。
求组合的时候,要防止两个int相乘溢出! 所以不能把算式的分子都算出来,分母都算出来再做除法。需要在计算分子的时候,不断除以分母,
class Solution {
public:
int uniquePaths(int m, int n) {
long long numerator = 1; // 分子
int denominator = m - 1; // 分母
int count = m - 1;
int t = m + n - 2;
while (count--) {
numerator *= (t--);
while (denominator != 0 && numerator % denominator == 0) {
numerator /= denominator;
denominator--;
}
}
return numerator;
}
};
边栏推荐
- Programming hodgepodge (4)
- 使用Loadrunner进行性能测试
- Use Patroni callback script to bind VIP pit
- 路网编辑器技术预研
- The idea setting recognizes the .sql file type and other file types
- Dynamic programming of the division of numbers
- 文献管理工具 | Zotero
- How to dynamically add script dependent scripts
- centos 安装postgresql13 指定版本
- 10 Convolutional Neural Networks for Deep Learning 3
猜你喜欢
随机推荐
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.4 Matching declarations to definitions
Dynamic programming of the division of numbers
大型连锁百货运维审计用什么软件好?有哪些功能?
详解八大排序
8款最佳实践,保护你的 IaC 安全!
[Skill] Using Sentinel to achieve priority processing of requests
Tactile intelligent sharing - SSD20X realizes upgrade display progress bar
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
基于gRPC编写golang简单C2远控
看DevExpress丰富图表样式,如何为基金公司业务创新赋能
深度学习环境配置
C Expert Programming Chapter 4 The Shocking Fact: Arrays and Pointers Are Not the Same 4.3 What is a Declaration and What is a Definition
ADC噪声全面分析 -03- 利用噪声分析进行实际设计
Mini program + e-commerce, fun new retail
解决错误:npm WARN config global `--global`, `--local` are deprecated
如何将 DevSecOps 引入企业?
少年成就黑客,需要这些技能
Turn: Management is the love of possibility, and managers must have the courage to break into the unknown
Gartner 权威预测未来4年网络安全的8大发展趋势
读者让我总结一波 redis 面试题,现在肝出来了









