算法之爬楼梯

版权声明:虽然写的很菜,但我也是有版权的! https://blog.csdn.net/weixin_42093825/article/details/83547762

题目:假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

沙雕解法一:利用递归,就是最后一步一定是前一步走一步或倒退两步走两步,超时!

#include "pch.h"
#include <iostream>
#include <string>

using namespace std;

int add(int n)
{
	if (n == 1|| n == 2)
		return n;
	else
		return add(n - 1) + add(n - 2);
}

int main()
{
	int n;
	cin >> n;
	if (n <= 0)
		cout << "error number" << endl;
	else
		cout << add(n) << "种方法。" << endl;
}

好的解法:利用循环,时空复杂度都较小

class Solution {
public:
    int climbStairs(int n) 
    {
        if (n<=0)
           return 0;
        else
        {
           if(n==1||n==2)
               return n;        
           else
           {
             int a=1;
             int b=2;
             int current = 0;
             for(int i=3;i<=n;i++)
             {
                 current = a+b;
                 a = b;
                 b = current;
             }
             return current;
           }
        }
    }
};

排名30万。
以及今天犯了一个沙雕错误,都不好意思说

猜你喜欢

转载自blog.csdn.net/weixin_42093825/article/details/83547762