算法课第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].


本题不算太难的动态规划问题,不过结合了二维平面的图形,显得稍微有趣和特殊。之后我还会对其他各种类型的动态规划都尝试做更多练习。


0 0
原创粉丝点击