Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 09e2050

Browse files
Climbing stairs
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent 46c62dc commit 09e2050

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

070_climbing_stairs/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test climb_stairs.c

070_climbing_stairs/climb_stairs.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
static int recursive(int n, int *count)
6+
{
7+
if (n == 0) {
8+
return 0;
9+
} else if (count[n] > 0) {
10+
return count[n];
11+
} else {
12+
if (n >= 1) {
13+
count[n] += recursive(n - 1, count);
14+
}
15+
if (n >= 2) {
16+
count[n] += recursive(n - 2, count);
17+
}
18+
return count[n];
19+
}
20+
}
21+
22+
static int climbStairs(int n)
23+
{
24+
int *count = malloc((n + 1) * sizeof(int));
25+
memset(count, 0, (n + 1) * sizeof(int));
26+
count[1] = 1;
27+
count[2] = 2;
28+
return recursive(n, count);
29+
}
30+
31+
int main(int argc, char **argv)
32+
{
33+
if (argc != 2) {
34+
fprintf(stderr, "Usage: ./test n\n");
35+
exit(-1);
36+
}
37+
38+
printf("%d\n", climbStairs(atoi(argv[1])));
39+
return 0;
40+
}

0 commit comments

Comments
 (0)