算法课第12周第1题——62. Unique Paths
来源:互联网 发布:mac版ae cc破解补丁 编辑:程序博客网 时间:2024/06/05 21:02
题目描述:
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
程序代码:
class Solution {public:int uniquePaths(int m, int n) {// 建立一个二维数组vector<int> temp(n, 0);vector<vector<int> > f(m, temp);// (0,0)处可到达路径数为1f[0][0] = 1;// (i, j)处可到达路径数为其上或左处之和// 注意处理边界处for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (i == 0 && j == 0) {continue;}if (i == 0) {f[i][j] = f[i][j - 1];}else if (j == 0) {f[i][j] = f[i - 1][j];}else {f[i][j] = f[i - 1][j] + f[i][j - 1];}}}return f[m - 1][n - 1];}};
简要题解:
本题运用了动态规划的算法。
先理解题意。本题需要从左上角的起点到右下角的终点(每次只能往下或往右走一步),求出总共可能的路径数量。
要解出本题,需要考虑一个二维平面的坐标。如下图所示:
、
在上图中,一般的点,如点a处,只可能从其上面的点(b点)或左边的点(c点)走到。因此,点a处的路径数即为点b和点c处路径数的和,即得到转移方程:
f[i][j] = f[i - 1][j] + f[i][j - 1]
但要注意特殊情况,也就是边界上的点。若在最上方一排的点,其i = 0, 没有上方的点可以到达此点,只有左边的点可以到达。 此时其转移方程为:f[i][j] = f[i][j - 1]
同理,若在最左边一列的点,转移方程则为:f[i][j] = f[i - 1][j] 。
接着要注意设置初始条件,即f[0][0] = 1, 表示从起点到起点有1条路径。
最后,输出结果即为f[m-1][n-1].
本题不算太难的动态规划问题,不过结合了二维平面的图形,显得稍微有趣和特殊。之后我还会对其他各种类型的动态规划都尝试做更多练习。
- 算法课第12周第1题——62. Unique Paths
- 算法课第12周第2题——63. Unique Paths II
- 算法第14周Unique Paths[medium]
- 算法第14周Unique Paths II[medium]
- LeetCode OJ 第63题Unique Paths ||
- Algorithms—62.Unique Paths
- 【leetcode】第62题 Unique Paths 题目+解析+JAVA代码
- 算法课第八周作业 | Unique Paths
- 算法题——Unique Paths(C++)动态规划
- LeetCode算法题——Unique Paths I & II
- 算法系列——Unique Paths
- LeetCode—Unique Paths
- leetcode——Unique Paths & Unique PathsⅡ
- 【leetcode】第63题 Unique Paths II 题目+解析+JAVA代码
- Unique Paths 解题研究,面试题练习第三天
- LeetCode——Unique Paths
- LeetCode——Unique Paths
- Leetcode——Unique Paths
- 代码selenium自动化执行指定路径下的所有用例文件
- Zookeeper与Paxos
- PAT1058 选择题(20)
- python3.5下安装numpy,scipy,sklearn,pandas,matplotlib,jieba,requests
- 2017年5月14日爱奇艺算法比赛
- 算法课第12周第1题——62. Unique Paths
- 深入理解JavaScript系列(11):执行上下文(Execution Contexts)
- UML---面向对象与面向过程
- 大学生程序设计邀请赛(华东师范大学)A
- A+B Problem
- RocketMQ源码解析:Message顺序发送与消费
- 单点登录系统
- 期中理论题总结
- 【源码分析】Volley用法及源码分析