LeetCode_Unique Paths

时间:2022-08-15 09: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?

  方法一: DFS 大数据超时

class Solution {
public:
void DFS(int i, int j, int m, int n){
if( i== m && j == n){
result++;
}
if(j+ <= n) DFS(i, j+,m,n);
if(i+ <= m) DFS(i+,j,m,n);
}
int uniquePaths(int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
result = ;
DFS(,,m,n);
return result;
}
private:
int result;
};

  方法二:动态规划。 grid[i][j] = grid[i-1][j]+grid[i][j-1]

class Solution {
public:
int uniquePaths(int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> grid(m,vector<int>(n,));
for(int i = ; i< n;i++) grid[][i] = ;
for(int i = ; i< m;i++) grid[i][] = ; for(int i = ; i< m; i++)
for(int j = ; j < n; j++)
grid[i][j] = grid[i-][j] + grid[i][j-];
return grid[m-][n-] ; }
};