File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ You are climbing a stair case. It takes n steps to reach to the top.
2
+
3
+ Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
4
+
5
+ ** Note** : Given n will be a positive integer.
6
+
7
+ Example 1:
8
+
9
+ ```
10
+ Input: 2
11
+ Output: 2
12
+ Explanation: There are two ways to climb to the top.
13
+
14
+ 1. 1 step + 1 step
15
+ 2. 2 steps
16
+ ```
17
+ Example 2:
18
+ ```
19
+ Input: 3
20
+ Output: 3
21
+ Explanation: There are three ways to climb to the top.
22
+
23
+ 1. 1 step + 1 step + 1 step
24
+ 2. 1 step + 2 steps
25
+ 3. 2 steps + 1 step
26
+ ```
27
+ ** 分析**
28
+ d(0) = 1
29
+
30
+ d(1) = 1
31
+
32
+ d(2) = d(2-1) + d(2-2)
33
+
34
+ d(3) = d(3-1) + d(3-2)
35
+
36
+ ……
37
+ Fibonacci数列,定义如下
38
+
39
+ ` f(1)=1,f(2)=1,f(n)=f(n-1)+f(n-2),n>2 `
40
+
41
+ ** 代码**
42
+ ```
43
+ /**
44
+ * Fibonacci数列,定义如下
45
+ * f(1)=1,f(2)=1,f(n)=f(n-1)+f(n-2),n>2
46
+ *
47
+ **/
48
+
49
+ class Solution {
50
+ public int climbStairs(int n) {
51
+ if (n<=1)
52
+ return 1;
53
+
54
+ int oneStep=1,twoStep = 1,res = 0;
55
+
56
+ for (int i = 2; i <= n; i++) {
57
+ res = oneStep + twoStep;
58
+ twoStep = oneStep;
59
+ oneStep = res;
60
+ }
61
+ return res;
62
+ }
63
+ }
64
+ ```
You can’t perform that action at this time.
0 commit comments