LeetCode-Unique Paths的一种算法
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?
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:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
题目要求很简单,就是给定一个m x n的方格,左上角为起点,右下角为终点,只能向右或向下移动,问从起点到终点的路径有多少种。
该问题解法有很多种,可以使用DFS、BFS、动态规划、纯数学计算多种方式实现,但是DFS和BFS很容易以为时间或空间的开销太大而报错,于是在这里,我决定使用动态规划的思想实现算法。
动态规划核心思想就是,使用一个数组存储到达该位置的路径数,如此一来,在终点位置存储的就是到达终点位置的路径数。
需要注意的是,起点位置设置为(0, 0)计算路径的位置从(1, 1)开始,因为按照本算法,每次循环是让遍历的点计算其左边和上边的点的路径之和(即前一位置的路径数)。
算法如下
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> vec(n, 1);
vector<vector<int>> vect(m, vec); //二维数组用以保存路径数
//双重循环计算路径数
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
//到达该位置的路径数量为左边和上边的路径数量之和
vect[i][j] = vect[i-1][j]+vect[i][j-1];
}
}
//返回右下角终点的值,即为到达终点的路径数
return vect[m-1][n-1];
}
};
本次算法难点在于找到动态规划的递推规律,只要找到其规律,即可迅速得到答案。
由于使用了双重循环,所以该算法的时间复杂度为O(m*n)。