File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ def staircase (num ):
2
+ if num <= 0 :
3
+ return
4
+ if num == 1 :
5
+ return 1
6
+ elif num == 2 :
7
+ return 2
8
+ elif num == 3 :
9
+ return 4
10
+ return staircase (num - 1 )+ staircase (num - 2 )+ staircase (num - 3 )
11
+
12
+ # caching the output to get faster implementation of the function
13
+ def staircase_with_hashmap (num ):
14
+ num_dict = dict ({})
15
+ return staircase_faster (num ,num_dict )
16
+
17
+ def staircase_faster (num ,num_dict ):
18
+ if num <= 0 :
19
+ return
20
+ if num == 1 :
21
+ output = 1
22
+ elif num == 2 :
23
+ output = 2
24
+ elif num == 3 :
25
+ output = 4
26
+ else :
27
+ if (num - 1 ) in num_dict :
28
+ n1 = num_dict [num - 1 ]
29
+ else :
30
+ n1 = staircase (num - 1 )
31
+ if (num - 2 ) in num_dict :
32
+ n2 = num_dict [num - 2 ]
33
+ else :
34
+ n2 = staircase (num - 2 )
35
+ if (num - 3 ) in num_dict :
36
+ n3 = num_dict [num - 3 ]
37
+ else :
38
+ n3 = staircase (num - 3 )
39
+ output = n1 + n2 + n3
40
+ num_dict [num ] = output
41
+ return output
42
+
43
+
44
+
45
+ print (staircase_with_hashmap (3 ))
You can’t perform that action at this time.
0 commit comments