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