0%

62. Unique Paths

62. Unique Paths

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int uniquePaths(int m, int n) {
return path(m, n);
}
private:
int path(int m, int n)
{
if(m == 1 || n == 1)
return 1;

return path(m - 1, n) + path(m, n - 1);
}
};

Time Limit Exceeded

动态规划,划分为子路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 1));
for(size_t i = 1; i < m; ++i)
{
for(size_t j = 1; j < n; ++j)
{
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
};

空间优化

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> dp(n, 1);
for(int i = 1; i < m; ++i)
for(int j = 1; j < n; ++j)
dp[j] += dp[j - 1];
return dp.back();
}
};