Skip to content

Commit 75654d3

Browse files
add a solution to 70 and tests
1 parent 92f91c1 commit 75654d3

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

src/main/java/com/fishercoder/solutions/_70.java

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,21 @@
44
* 70. Climbing Stairs
55
66
You are climbing a stair case. It takes n steps to reach to the top.
7-
87
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
98
109
Note: Given n will be a positive integer.
1110
1211
Example 1:
13-
1412
Input: 2
1513
Output: 2
1614
Explanation: There are two ways to climb to the top.
17-
1815
1. 1 step + 1 step
1916
2. 2 steps
2017
2118
Example 2:
22-
2319
Input: 3
2420
Output: 3
2521
Explanation: There are three ways to climb to the top.
26-
2722
1. 1 step + 1 step + 1 step
2823
2. 1 step + 2 steps
2924
3. 2 steps + 1 step
@@ -32,6 +27,10 @@
3227

3328
public class _70 {
3429
public static class Solution1 {
30+
/**
31+
* O(n) time
32+
* O(n) space
33+
* */
3534
public int climbStairs(int n) {
3635
if (n == 1) {
3736
return n;
@@ -45,4 +44,24 @@ public int climbStairs(int n) {
4544
return dp[n];
4645
}
4746
}
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+
}
4867
}

src/test/java/com/fishercoder/_70Test.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,21 @@
88

99
public class _70Test {
1010
private static _70.Solution1 solution1;
11+
private static _70.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _70.Solution1();
16+
solution2 = new _70.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals(3, solution1.climbStairs(3));
2022
}
23+
24+
@Test
25+
public void test2() {
26+
assertEquals(3, solution2.climbStairs(3));
27+
}
2128
}

0 commit comments

Comments
 (0)