当前位置:网站首页>力扣: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;
}
};
边栏推荐
- docker安装mysql与宿主机相差8小时的问题。
- What are the steps for how to develop a mall system APP?
- Explain detailed explanation and practice
- 基于gRPC编写golang简单C2远控
- Typora 使用保姆级教程 | 看这一篇就够了 | 历史版本已被禁用
- 详解八大排序
- sql server如何得到本条记录与上一条记录的差异,即变动值
- What is the salary of a software testing student?
- OpenGL绘制圆
- How to dynamically add script dependent scripts
猜你喜欢
随机推荐
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.4 Matching declarations to definitions
企业需要知道的5个 IAM 最佳实践
3000 words, is take you understand machine learning!
Write golang simple C2 remote control based on gRPC
Towards Real-Time Multi-Object Tracking (JDE)
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
C专家编程 第4章 令人震惊的事实:数组和指针并不相同 4.4 使声明与定义相匹配
小程序 + 电商,玩转新零售
7-3 LVS+Keepalived Cluster Description and Deployment
Introduction and application of go module
OpenGL绘制圆
word 公式编辑器 键入技巧 | 写数学作业必备速查表
[C language advanced] program environment and preprocessing
有趣的 Kotlin 0x0E:DeepRecursiveFunction
JVM Notes
3000字,一文带你搞懂机器学习!
Cache pool of unity framework
某母婴小程序加密参数解密
8款最佳实践,保护你的 IaC 安全!
字节最爱问的智力题,你会几道?








