forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Leo Ma <[email protected]>
- Loading branch information
1 parent
46c62dc
commit 09e2050
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test climb_stairs.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |