Skip to content

Commit 7b9342f

Browse files
committed
Add C++ solutions for leetcode 62 and leetcode 63.
1 parent f7c9e70 commit 7b9342f

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
#include<cstring>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
int uniquePaths(int m, int n) {
10+
int dp[m][n]; // dp数组 - dp[i][j]: 从位置(0, 0)走到位置(i, j)的unique path的数量
11+
memset(dp, 0, sizeof(dp));
12+
dp[0][0] = 1; /* 原点位置(0, 0)只有不动这一种走法, 对矩阵中间某个位置 dp[i][j] = dp[i-1][j] + dp[i][j-1] */
13+
for (int i = 0; i < m; i++)
14+
{
15+
for (int j = 0; j < n; j++)
16+
{
17+
if (i >= 1)
18+
dp[i][j] += dp[i-1][j];
19+
if (j >= 1)
20+
dp[i][j] += dp[i][j-1];
21+
}
22+
}
23+
return dp[m - 1][n - 1];
24+
}
25+
};
26+
27+
// Test
28+
int main()
29+
{
30+
Solution sol;
31+
int m = 3;
32+
int n = 7;
33+
auto res = sol.uniquePaths(m, n);
34+
cout << res << endl;
35+
36+
return 0;
37+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
#include<cstring>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
int uniquePathsWithObstacles(vector<vector<int>>& G) {
10+
const int m = G.size();
11+
const int n = G[0].size();
12+
int dp[m][n]; // dp数组 - dp[i][j]: 从位置(0, 0)走到位置(i, j)的unique path的数量
13+
memset(dp, 0, sizeof(dp));
14+
dp[0][0] = 1; /* 原点位置(0, 0)只有不动这1种走法, 对矩阵中间某个位置 dp[i][j] = dp[i-1][j] + dp[i][j-1] */
15+
for (int i = 0; i < m; i++)
16+
{
17+
for (int j = 0; j < n; j++)
18+
{
19+
if (G[i][j] == 1)
20+
dp[i][j] = 0;
21+
else
22+
{
23+
if (i >= 1)
24+
dp[i][j] += dp[i-1][j];
25+
if (j >= 1)
26+
dp[i][j] += dp[i][j-1];
27+
}
28+
}
29+
}
30+
return dp[m-1][n-1];
31+
}
32+
};
33+
34+
// Test
35+
int main()
36+
{
37+
Solution sol;
38+
vector<vector<int>> G =
39+
{
40+
{0, 0, 0},
41+
{0, 1, 0},
42+
{0, 0, 0}
43+
};
44+
auto res = sol.uniquePathsWithObstacles(G);
45+
cout << res << endl;
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)