力扣算法题—070爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1.  1 阶 + 1 阶
2.  2 阶

示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1.  1 阶 + 1 阶 + 1 阶
2.  1 阶 + 2 阶
3.  2 阶 + 1 阶


 1 #include "_000库函数.h"
 2 //感觉有好多种爬法
 3 //我又想到了用全排列
 4 //又是超时,一用到全排列就超时
 5 class Solution {
 6 public:
 7     int climbStairs(int n) {
 8         vector<int>v(n, 1);//开始使用一节一节的爬法
 9         int res = 1;
10         int num1 = n, num2 = 0;//一节与二节的数量
11         while (1) {
12             sort(v.begin(), v.end());
13             while (next_permutation(v.begin(), v.end())) ++res;
14             v.clear();
15             num1 -= 2;
16             if (num1 < 0)break;
17             ++num2;//两个一节用一个二节代替
18             v.insert(v.end(), num1, 1);
19             v.insert(v.end(), num2, 2);
20             ++res;
21         }
22         return res;
23     }
24 };
25 
26 
27 //使用动态规划思想
28 class Solution {
29 public:
30     int climbStairs(int n) {
31         if (n <= 1) return 1;
32         vector<int> dp(n);
33         dp[0] = 1; dp[1] = 2;
34         for (int i = 2; i < n; ++i) {
35             dp[i] = dp[i - 1] + dp[i - 2];
36         }
37         return dp.back();
38     }
39 };
40 
41 
42 //优化点的代码
43 class Solution {
44 public:
45     int climbStairs(int n) {
46         int a = 1, b = 1;
47         while (n--) {
48             b += a;
49             a = b - a;
50         }
51         return a;
52     }
53 };
54 void T070() {
55     Solution s;
56     cout << "1:    " << s.climbStairs(1) << endl;
57     cout << "2:    " << s.climbStairs(2) << endl;
58     cout << "3:    " << s.climbStairs(3) << endl;
59     cout << "5:    " << s.climbStairs(5) << endl;
60 }
原文地址:https://www.cnblogs.com/zzw1024/p/10696764.html