File tree Expand file tree Collapse file tree 1 file changed +38
-14
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +38
-14
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
- /**Leetcode 70: You are climbing a stair case. It takes n steps to reach to the top.
3
+ /**
4
+ * 70. Climbing Stairs
5
+
6
+ You are climbing a stair case. It takes n steps to reach to the top.
7
+
8
+ Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
9
+
10
+ Note: Given n will be a positive integer.
11
+
12
+ Example 1:
13
+
14
+ Input: 2
15
+ Output: 2
16
+ Explanation: There are two ways to climb to the top.
17
+
18
+ 1. 1 step + 1 step
19
+ 2. 2 steps
20
+
21
+ Example 2:
22
+
23
+ Input: 3
24
+ Output: 3
25
+ Explanation: There are three ways to climb to the top.
26
+
27
+ 1. 1 step + 1 step + 1 step
28
+ 2. 1 step + 2 steps
29
+ 3. 2 steps + 1 step
30
+
31
+ */
4
32
5
- Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?*/
6
33
public class _70 {
34
+ public static class Solution1 {
7
35
//classical dp problem
8
36
public int climbStairs (int n ) {
9
- if (n < 1 ) {
10
- return 0 ;
11
- }
12
- if (n < 4 ) {
13
- return n ;
14
- }
37
+ if (n < 1 ) {
38
+ return 0 ;
39
+ } else if (n < 4 ) {
40
+ return n ;
41
+ } else {
15
42
int [] dp = new int [n + 1 ];
16
43
//the number of ways to reach step n could be calculated from n-1 and n-2
17
44
dp [1 ] = 1 ;
18
45
dp [2 ] = 2 ;
19
46
for (int i = 3 ; i <= n ; i ++) {
20
- dp [i ] = dp [i - 1 ] + dp [i - 2 ];
47
+ dp [i ] = dp [i - 1 ] + dp [i - 2 ];
21
48
}
22
49
return dp [n ];
50
+ }
23
51
}
24
-
25
- public static void main (String ... strings ) {
26
- _70 test = new _70 ();
27
- System .out .println (test .climbStairs (6 ));
28
- }
52
+ }
29
53
}
You can’t perform that action at this time.
0 commit comments