Leetcode_62_UniquePaths_唯一路径数

这个是Leetcode上的第62个题目,属于动态规划DynamicProgramming的Medium题目。
后来才发现完美世界的一道算法题就是根据这个题目改造的,有兴趣的同学可以看下这道题目:
https://www.nowcoder.com/discuss/173242?type=0&order=0&pos=17&page=1

/*JianzhiOffer_62_UniquePaths_唯一路径数/
/**
* JianzhiOffer_62_UniquePaths_唯一路径数
* 题目介绍:
* 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>
* start 0 0 0 0 0 0
* 0 0 0 0 0 0 0
* 0 0 0 0 0 0 finish
* Above is a 7 x 3 grid. How many possible unique paths are there?
* Note: m and n will be at most 100.
* <p>
* Example 1:
* Input: m = 3, n = 2
* Output: 3
* Explanation:
* From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
* 1. Right -> Right -> Down
* 2. Right -> Down -> Right
* 3. Down -> Right -> Right
* Example 2:
* Input: m = 7, n = 3
* Output: 28
* <p>
*
* 解题思路:动态规划。
* 从finish终点倒着推向start点。
* dp[][]数组的每一个元素表示当前该点作为start点到finish点的路径数。
* 初始化:
* dp[rows - 1][i] = 1;
* dp[i][cols - 1] = 1;
* 动态规划表达式:
* dp[i][j] = dp[i][j + 1] + dp[i + 1][j];
* 最终返回dp[0][0]即可。
*/
public int uniquePaths(int cols, int rows) {
if (cols < 1 || rows < 1) return 0;
if (cols == 1 || rows == 1) return 1;
int[][] dp = new int[rows][cols];
//init
for (int i = 0; i < cols - 1; i++) dp[rows - 1][i] = 1;//最后一行初始化
for (int i = 0; i < rows - 1; i++) dp[i][cols - 1] = 1;//最后一列初始化
for (int i = rows - 2; i >= 0; i--) {
for (int j = cols - 2; j >= 0; j--) {
dp[i][j] = dp[i][j + 1] + dp[i + 1][j];
}
}
return dp[0][0];
}

#leetcode##笔试题目#
全部评论

相关推荐

不愿透露姓名的神秘牛友
2024-12-30 18:02
程序员牛肉:1.可以标记一下自己的学校是985,有一些hr可能没想到你这个院校是985的。 2.简历所呈现出来的能力还是有点差的,苍穹外卖+黑马点评。这在java技术域里面也就是刚学三四个月的样子,大厂现在招人少,小厂又更加希望你能直接过来干活。就你简历上呈现出来的能力,确实是有点难找,肉眼可见的不懂技术。 第一个项目中:简单的使用redis也算是亮点嘛?使用jwt,threadlocal也算是亮点?你不就是调了几个包嘛?Nginx作为服务器也能写出来,这不是前端的活嘛? 第二个项目中:分布式锁+mq消息队列+Lua队列。真没啥好问的。属于面试官看一眼就阳痿的简历,没有任何想提问的欲望。 我给你建议是好好的挖一挖这个项目吧,其实苍穹外卖和黑马点评这两个项目很不错了,只不过是太烂大街了导致面试官没啥问的兴趣,所以不太推荐写简历上。
点赞 评论 收藏
分享
01-07 15:50
四川大学 Java
看日出看日落:好好背八股,做算法。我身边跟你bg差不多的基本都大厂暑期
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务