袋鼠蹦蹦跳问题

#include <iostream>

using namespace std;
//袋鼠一次能跳动1米或者三米,在给定距离的情况下求方法数
//第一种方法叫做递归 第二种方法叫做递推利用一维数组保存计算当前结果所需要的前面的结果
class KangarooRun{
    private:
        int distance;
        int result[50];
    //这些函数不能写成私有的
    public:
    KangarooRun(int distance){
        this->distance = distance;
    }

    int calculate(){
        result[1] = 1;
        result[2] = 1;
        result[3] = 2;
        for(int i=4;i<=distance;i++){
            result[i] = result[i-1]+result[i-3];
        }
        return result[distance];
    }

    int calculate2(int distance){
        if(distance==1||distance==2) return 1;
        else  if(distance==3) return 2;
        else return calculate2(distance-1)+calculate2(distance-3);
    }

};


int main()
{
    int  distance;
    cout<<"请输入距离distance:";
    cin>>distance;
    KangarooRun Test(distance);
    cout <<Test.calculate()<< endl<<Test.calculate2(distance)<<endl;
    return 0;
}

你可能感兴趣的:(c)