类别:dynamic programming
难度:medium
题目描述
https://leetcode.com/problems/unique-paths/description/
算法分析
单纯的只往下走或者是单纯的只往右走,都只有一种可能的走法,所以初始化的时候path[i][0] = path[0][j] = 1
对于每一个位置,走到这里的上一步可能是从上面下来或者是从左边过来,所以path[i][j] = path[i - 1][j] + path[i][j - 1]
代码实现
// for every position, can be from left or up, and so there is
// path[i][j] = path[i - 1][j] + path[i][j - 1];
class Solution {
public:
int uniquePaths(int m, int n) {
// 二维数组
vector<vector<int> > path(m, vector<int>(n,1));
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
path[i][j] = path[i - 1][j] + path[i][j - 1];
}
}
return path[m-1][n-1];
}
};
本文介绍了一种使用动态规划解决LeetCode上Unique Paths问题的方法。该问题要求计算从左上角到右下角的不同路径数量,仅允许向下或向右移动。通过建立一个二维数组path来记录到达每个格子的不同路径数,最终返回path[m-1][n-1]即为所求。

473

被折叠的 条评论
为什么被折叠?



