File tree Expand file tree Collapse file tree 2 files changed +31
-5
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Original file line number Diff line number Diff line change 4
4
* 70. Climbing Stairs
5
5
6
6
You are climbing a stair case. It takes n steps to reach to the top.
7
-
8
7
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
9
8
10
9
Note: Given n will be a positive integer.
11
10
12
11
Example 1:
13
-
14
12
Input: 2
15
13
Output: 2
16
14
Explanation: There are two ways to climb to the top.
17
-
18
15
1. 1 step + 1 step
19
16
2. 2 steps
20
17
21
18
Example 2:
22
-
23
19
Input: 3
24
20
Output: 3
25
21
Explanation: There are three ways to climb to the top.
26
-
27
22
1. 1 step + 1 step + 1 step
28
23
2. 1 step + 2 steps
29
24
3. 2 steps + 1 step
32
27
33
28
public class _70 {
34
29
public static class Solution1 {
30
+ /**
31
+ * O(n) time
32
+ * O(n) space
33
+ * */
35
34
public int climbStairs (int n ) {
36
35
if (n == 1 ) {
37
36
return n ;
@@ -45,4 +44,24 @@ public int climbStairs(int n) {
45
44
return dp [n ];
46
45
}
47
46
}
47
+
48
+ public static class Solution2 {
49
+ /**
50
+ * O(n) time
51
+ * O(1) space
52
+ * */
53
+ public int climbStairs (int n ) {
54
+ if (n == 1 ) {
55
+ return n ;
56
+ }
57
+ int stepOne = 1 ;
58
+ int stepTwo = 2 ;
59
+ for (int i = 3 ; i <= n ; i ++) {
60
+ int tmp = stepTwo ;
61
+ stepTwo = stepOne + stepTwo ;
62
+ stepOne = tmp ;
63
+ }
64
+ return stepTwo ;
65
+ }
66
+ }
48
67
}
Original file line number Diff line number Diff line change 8
8
9
9
public class _70Test {
10
10
private static _70 .Solution1 solution1 ;
11
+ private static _70 .Solution2 solution2 ;
11
12
12
13
@ BeforeClass
13
14
public static void setup () {
14
15
solution1 = new _70 .Solution1 ();
16
+ solution2 = new _70 .Solution2 ();
15
17
}
16
18
17
19
@ Test
18
20
public void test1 () {
19
21
assertEquals (3 , solution1 .climbStairs (3 ));
20
22
}
23
+
24
+ @ Test
25
+ public void test2 () {
26
+ assertEquals (3 , solution2 .climbStairs (3 ));
27
+ }
21
28
}
You can’t perform that action at this time.
0 commit comments