POJ put apple problem (recursive)

First we imagine that there is a function count(m,n) that can put m apples into n plates.

 

According to the relationship between n and m, it can be further analyzed:

  There is only one way when the special m <= 1|| n <= 1;

  When m < n, even if one apple per plate cannot fill all the plates, the title allows some plates to be left empty, so we can remove the empty plates, that is count ( m , n ) = count ( m , m );

  When m >= n, there are two cases:

  There is an empty plate among n plates, when there is an empty plate, count ( m , n ) = count ( m , n - 1 );

  There are no empty plates in the n plates. When there are no empty plates, that is to say, there is at least one apple in each plate. Fill all the plates first, then there will be m - n apples left, so now the problem becomes m - How many ways can n apples be placed on n plates, i.e. count ( m - n , n ).

      So when m>=n, the total number of apples placed is count ( m , n - 1 ) + count ( m - n , n ) times.

  The specific code is implemented as follows:

#include <iostream>
using namespace std;
int count(int m, int n)
{

    if (m <=1|| n <= 1) 
        return 1;
    if (m < n)
        return count(m, m);
    else
        return count(m, n - 1) + count(m - n, n);
}
intmain ()
{
    int m, n;
    cin >> m >> n;
    
    cout << count(m, n) << endl;

    return 0;
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161350&siteId=291194637