递归~放苹果



递归代码:

#include<iostream>
using namespace std;

int count(int m, int n)
{
    if(m == 0 || n == 1)
        return 1;
    else if(m < n)
        return count(m, m);
    return count(m, n-1) + count(m-n, n);
}
int main()
{
    int n_case, m, n;
    cout << "Enter n_case: " << endl;
    cin >> n_case;
    while(n_case--)
    {
        cout << "Enter two intengers: " << endl;
        cin >> m >> n;
        cout << "The total path is: " << count(m, n) << endl;
    }
}


运行结果:

Enter n_case:
2
Enter two intengers:
7 3
The total path is: 8
Enter two intengers:
10 8
The total path is: 40

Process returned 0 (0x0)   execution time : 4.922 s
Press any key to continue.

非递归代码:

#include<iostream>
using namespace std;

int main()
{
    int n_case, m, n, a[10][10] = {0};
    cout << "Enter n_case(0<= n_case <= 20): " << endl;
    cin >> n_case;
    cout << "Enter intengers(m refers to the apples, and the n refers to the tray,1 <= m,n <= 10): " << endl;
    for(int i= 0,j = 1; i <= m; ++i)
        a[i][j] = 1;           //只有一个盘子时,无论苹果多少都只有一种放法
    for(int i = 0, j = 0; j <= n; ++j)
        a[i][j] = 1;        //没有苹果时,定义为一种放法
    for(int i = 1; i <= m; ++i)
        for(int j = 1; j <= i; ++j)
        {
            if((i-j) < j)
                a[i][j] = a[i][j-1] + a[i-j][i-j];
            else
                a[i][j] = a[i][j-1] + a[i-j][j];
        }
    while(n_case--)
    {
        cin >> m >> n;
        cout << "The total path is: " << endl;
        if(m < n)
            cout << a[m][m] << endl;
        else
            cout << a[m][n] << endl;
    }
    return 0;
}

说明:这个代码有问题,m或n输入值一旦超过10的话,就出错,问题出在那里还不清楚,有待改正……

同时欢迎提出宝贵意见,以帮助我改进,不胜感激!!!

——桑海整理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值