LeetCode题解——Unique Path(DP与优化)

时间:2023-03-09 15:40:21
LeetCode题解——Unique Path(DP与优化)

题目: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?

题意:在m*n的网格中,从左下角一步步走到右上角,有多少种可能的走法(每次只能横或竖移动一步)

    在第一象限的话,也就是每次走一步从(0,0)走到(m,n)有多少种走法

思路:考虑这是一个递推的问题,根据DP思想,有递推公式

LeetCode题解——Unique Path(DP与优化)

我的代码比较短,因为memset只能置0或者-1,可以把数组置为-1,然后和取负就是所求结果了。

class Solution {
public:
int uniquePaths(int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int f[m][n];
memset(f, -, sizeof(int) * m * n); //数组全部置-1
for (int i = ; i < m; i++) { //求和
for (int j = ; j < n; j++) {
f[i][j] = f[i - ][j] + f[i][j - ];
}
}
return -f[m - ][n - ]; //取负
}
};

时间复杂度O(m*n),那么可不可以继续优化呢?

上面采用的是二维数组,现在可以用一位数组取代之,则

Fn=Fn-1+Fn;

class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> vec(n, );
for(int i=; i<m; ++i){
for(int j=; j<n; ++j){
vec[j]+=vec[j-];
}
}
return vec[n-];
}
};