-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUniquePath.c
62 lines (56 loc) · 1.21 KB
/
UniquePath.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//该版本空间复杂度太高,可以优化
int uniquePaths(int m, int n)
{
int path[m][n];
int i, j;
for (i = 0; i < n; i++)
path[0][i] = 1;
for (i = 0; i < m; i++)
path[i][0] = 1;
for (i = 1; i < m; i++)
{
for (j = 1; j < n; j++)
path[i][j] = path[i-1][j] + path[i][j-1];
}
return path[m-1][n-1];
}
//空间复杂度较低的版本
int uniquePaths(int m, int n)
{
int path[2][n];
int i, j;
if (m == 1 || n == 1)
return 1;
for (i = 0; i < n; i++)
path[0][i] = 1;
for (i = 0; i < 2; i++)
path[i][0] = 1;
for (j = 1; j < m; j++)
{
for (i = 1; i < n; i++)
path[1][i] = path[1][i-1] + path[0][i];
for (i = 1; i < n; i++)
path[0][i] = path[1][i];
}
return path[1][n-1];
}
//空间复杂度更低的版本
int uniquePaths(int m, int n)
{
int path[n];
int i, j;
int left, cur;
for (i = 0; i < n; i++)
path[i] = 1;
for (i = 1; i < m; i++)
{
left = 1;
for (j = 1; j < n; j++)
{
cur = left + path[j];
left = cur;
path[j] = cur;
}
}
return path[n-1];
}