File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ all :
2
+ gcc -O2 -o test climb_stairs.c
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments