Skip to content

Commit

Permalink
Climbing stairs
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Oct 6, 2017
1 parent 46c62dc commit 09e2050
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 070_climbing_stairs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test climb_stairs.c
40 changes: 40 additions & 0 deletions 070_climbing_stairs/climb_stairs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int recursive(int n, int *count)
{
if (n == 0) {
return 0;
} else if (count[n] > 0) {
return count[n];
} else {
if (n >= 1) {
count[n] += recursive(n - 1, count);
}
if (n >= 2) {
count[n] += recursive(n - 2, count);
}
return count[n];
}
}

static int climbStairs(int n)
{
int *count = malloc((n + 1) * sizeof(int));
memset(count, 0, (n + 1) * sizeof(int));
count[1] = 1;
count[2] = 2;
return recursive(n, count);
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}

printf("%d\n", climbStairs(atoi(argv[1])));
return 0;
}

0 comments on commit 09e2050

Please sign in to comment.