From 09e20507ad99e79e0105660c86d9fe848a0b6154 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Fri, 6 Oct 2017 11:49:52 +0800 Subject: [PATCH] Climbing stairs Signed-off-by: Leo Ma --- 070_climbing_stairs/Makefile | 2 ++ 070_climbing_stairs/climb_stairs.c | 40 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 070_climbing_stairs/Makefile create mode 100644 070_climbing_stairs/climb_stairs.c diff --git a/070_climbing_stairs/Makefile b/070_climbing_stairs/Makefile new file mode 100644 index 0000000..8573363 --- /dev/null +++ b/070_climbing_stairs/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test climb_stairs.c diff --git a/070_climbing_stairs/climb_stairs.c b/070_climbing_stairs/climb_stairs.c new file mode 100644 index 0000000..2b0b31a --- /dev/null +++ b/070_climbing_stairs/climb_stairs.c @@ -0,0 +1,40 @@ +#include +#include +#include + +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; +}