栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

算法-递归:n级台阶走法问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法-递归:n级台阶走法问题

算法-递归 n级台阶,每一次只能选择迈一步或者迈两步,共有多少种走法
#include 
using namespace std;
//n级台阶,每一次只能选择迈一步或者迈两步,共有多少种走法

//方法一:采用递归,时间复杂度为n^2,对于第n级台阶来说,要么是走一步上来的,要么是走两步上来的
int step(int n){
    if(0 >= n){
        return 0;
    }else if(1 == n){
        return 1;
    }else if(2 == n){
        return 2;
    }else{ // n >= 3
        return step(n-1)+step(n-2);
    }
}

int main(){
    int n;
    while(cin>>n){
        cout << "走法为:"< 
#include 
using namespace std;
//n级台阶,每一次只能选择迈一步或者迈两步,共有多少种走法

//方法二:采用递归,时间复杂度为n,将n-2的值提前计算出来,只递归n-1
//0:first
//1:second
//2:first+second
//3:second+(first+second)
int step(int first,int second,int n){
    if(0 >= n){
        return 0;
    }else if(1 == n){
        return 1;
    }else if(2 == n){
        return 2;
    }else if (3 == n){
        return first+second;
    }else{ // n > 3
        return step(second,first+second,n-1);
    }
}

int main(){    
    int n;
    while(cin>>n){
        cout << "走法为:"<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/717098.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号