LeetCode算法题——Unique Paths I & II
来源:互联网 发布:java整型转换成字符串 编辑:程序博客网 时间:2024/06/11 00:47
题目概述
I:
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?
II:
Follow up for “Unique Paths”:
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0]]The total number of unique paths is 2.
分析
这两道题属于同一类型,因此集中讨论。
问题一是问题的原始版本,仅仅是简单讨论从一个m*n矩阵的左上角到右下角,有多少种移动的路径。最直观的方法就是使用动态规划,因为分析可知,第一行和第一排的格子,都只有唯一的移动路径可以到达;而要到达其他的任意格子,要么先到达该格子上方的格子,要么先到达该格子左边的格子,因此在计算到达改格子的方式数量时,只需要将到达其上方格子的方式数量与到达其左侧格子的方式数量相加即可。如此不断地迭代相加,最终直接返回最后一个格子的结果即可。具体代码如下:
int uniquePaths(int m, int n) { int** result = new int*[m]; for (int i = 0; i <= m; i++) result[i] = new int[n]; for (int i = 0; i < m; i++) result[i][0] = 1; for (int i = 0; i < n; i++) result[0][i] = 1; for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) result[i][j] = result[i-1][j] + result[i][j-1]; return result[m-1][n-1];}
时间复杂度和空间复杂度均为O(m*n)。
问题二中,出现了障碍物。因此,在进行遍历循环的时候,不能直接进行叠加,而应当根据当前格子是否存在障碍物进行判断。其他的大致流程,与问题一接近:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); if (m == 0 || n == 0) return 0; vector<vector<int> > dp(m, vector<int>(n, 0)); if (obstacleGrid[0][0] == 0) dp[0][0] = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (obstacleGrid[i][j] == 0) { if (i > 0) dp[i][j] += dp[i-1][j]; if (j > 0) dp[i][j] += dp[i][j-1]; } } } return dp[m-1][n-1];}
时间复杂度和空间复杂度均为O(m*n)。
总结
- 动态规划法在解决此类问题上简洁直观
- 事实上也可以使用一维数组,替代前文所述的二维数组方法。但在实验中发现,使用改进的一维数组进行动态规划,在时间效率上更低一些。
- LeetCode算法题——Unique Paths I & II
- [LeetCode]Unique Paths I & II
- 【LeetCode】Unique Paths I && II
- Unique Paths I | II leetcode
- LeetCode | Unique Paths I,II
- LeetCode——Unique Paths II
- LeetCode——Unique Paths II
- LeetCode——Unique Paths II
- leetcode 063 —— Unique Paths II
- Leetcode题集——unique-paths-ii
- LeetCode Solutions : Unique Paths I & II
- leetcode-62&63 Unique Paths I & II
- Leetcode(62)(63) Unique Paths I II
- [Leetcode] #62#63 Unique Paths I & II
- Unique Paths I & II
- Unique Paths I,II
- Unique Paths I II
- Unique Paths I,II
- JAVA通过访问页面中的URL实现Http文件下载到本地
- Ubuntu16.04 安装pycharm (tar.gz格式)
- jquery一周学习总结
- Jsch性能问题
- NFS作为根文件系统启动的几个关键点
- LeetCode算法题——Unique Paths I & II
- break跳出两重循环
- 实例详解Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化(一)
- Java实现 调用JdbcTemplate.batchUpdate方法批量更新
- bash的基本特性
- 在Android应用中使用Log打印日志信息
- C++实现堆栈
- Android四大组件--Service详解
- String.indexOf源码分析