leetcode【62】Unique Paths
程序员文章站
2022-06-04 17:38:55
...
问题描述:
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 7 x 3 grid. 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:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
源码:
第一眼一看,这不和剑指offer中的剑指offer-机器人的运动范围有点像嘛,喀喀喀编完了,最后超时,我抑郁了。(超时代码如下)当找到最后一行或者最后一列的时候,我还自作聪明的做了一点优化。
class Solution {
public:
int count = 0;
int uniquePaths(int m, int n) {
if(m<=1 || n<=1) return 1;
vector<bool> visit(m*n, false);
moving(visit, 0, 0, m, n);
return count;
}
void moving(vector<bool> &visit, int row, int col, int m, int n){
if(row == m-1 && col == n-1){
count++; return;
}
if(row==m-1 || col==n-1){
count++;
return;
}
if(isvalid(visit, row, col, m, n)){
visit[row*n+col] = true;
moving(visit, row+1, col, m, n);
moving(visit, row, col+1, m, n);
visit[row*n+col] = false;
}
}
bool isvalid(vector<bool> &visit, int row, int col, int m, int n){
if(row<m && col<n && !visit[row*n+col]){
return true;
}
return false;
}
};
最后想想不对额,只能上下,不就是个简单的动态规划嘛,我更抑郁了!!!
class Solution {
public:
int uniquePaths(int m, int n) {
if(m<=1 || n<=1) return 1;
vector<vector<int>> count(m, vector<int> (n, 0));
for(int i=0; i<m; i++) count[i][0] = 1;
for(int i=0; i<n; i++) count[0][i] = 1;
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
count[i][j] = count[i-1][j] + count[i][j-1];
}
}
return count[m-1][n-1];
}
};
稍微优化一下,想做优化的话,考虑一下一维的count
class Solution {
public:
int uniquePaths(int m, int n) {
if(m<=1 || n<=1) return 1;
vector<int> count(m*n, 0);
for(int i=0; i<m; i++) count[i*n] = 1;
for(int i=0; i<n; i++) count[i] = 1;
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
count[i*n + j] = count[(i-1)*n+j] + count[i*n + j-1];
}
}
return count[(m-1)*n + n-1];
}
};