1
+ // 最基础版,自顶向下的动态规划
2
+
3
+ // 超时了 21 / 45 test cases passed.
4
+ class Solution
5
+ {
6
+ public:
7
+ int climbStairs (int n)
8
+ {
9
+ if (n <= 2 )
10
+ return n;
11
+ else
12
+ return climbStairs (n - 1 ) + climbStairs (n - 2 );
13
+ }
14
+ };
15
+
16
+ // 第二个版本,自顶向下的动态规划+备忘录,可以看到加速效果非常明显
17
+ // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Climbing Stairs.
18
+ // Memory Usage: 9.1 MB, less than 5.02% of C++ online submissions for Climbing Stairs.
19
+ class Solution
20
+ {
21
+ public:
22
+ int climbStairs (int n)
23
+ {
24
+ unordered_map<int , int > hashmap;
25
+ return n <= 2 ? n : dp (hashmap, n);
26
+ }
27
+ private:
28
+ int dp (unordered_map<int , int >& hashmap, int n)
29
+ {
30
+ if (hashmap.find (n) == hashmap.end ())
31
+ {
32
+ int res = n <= 2 ? n : dp (hashmap, n - 1 ) + dp (hashmap, n - 2 );
33
+ hashmap.insert (pair<int , int >(n, res));
34
+ }
35
+ return hashmap.at (n);
36
+ }
37
+ };
38
+
39
+ // 第三个版本,自底向上的动态规划,使用递推而不是递归
40
+ // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Climbing Stairs.
41
+ // Memory Usage: 8.5 MB, less than 23.91% of C++ online submissions for Climbing Stairs.
42
+ class Solution
43
+ {
44
+ public:
45
+ int climbStairs (int n)
46
+ {
47
+ if (n <= 2 ) return n;
48
+
49
+ vector<int > res (n);
50
+ res[0 ] = 1 ; res[1 ] = 2 ;
51
+ for (int i = 2 ; i < n; ++i)
52
+ res[i] = res[i - 1 ] + res[i - 2 ];
53
+
54
+ return res[n];
55
+ }
56
+ };
57
+
58
+
59
+ // 第四个版本,自底向上的动态规划,常数级的空间复杂度
60
+ class Solution
61
+ {
62
+ public:
63
+ int climbStairs (int n)
64
+ {
65
+ if (n <= 2 ) return n;
66
+
67
+ int res, lres = 2 , llres = 1 ;
68
+ for (int i = 2 ; i < n; ++i)
69
+ {
70
+ res = lres + llres;
71
+ llres = lres;
72
+ lres = res;
73
+ }
74
+ return res;
75
+ }
76
+ };
0 commit comments