递归~放苹果

来源:互联网 发布:淘宝鹊桥app 编辑:程序博客网 时间:2024/05/16 18:52



递归代码:

#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的话,就出错,问题出在那里还不清楚,有待改正……

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

——桑海整理