放苹果(递归)

点击打开链接

m个苹果放入n个盘子有几种方法。

用递归,n个盘子有一个为空,或者n个盘子都至少有一个。

#include   
#include 
using namespace std;
int sharingapple(int m, int n){
	if (m == 1 || n == 1)//只有一个苹果或者只有一个盆子,则只有一种放法。
		return 1;
	else if (m < n)
		return sharingapple(m, m); //2个苹果放入3个盘子与2个苹果放入2个盆子是一样的
	else if (m>n)
		return sharingapple(m, n - 1) + sharingapple(m - n, n);//3个苹果放入2个盘子 可以理解为3个苹果放入一个盘子(有某一个空)的情况+一个苹果放入三个盘子(每个盘子都至少有一个苹果)的情况
	else
		return 1 + sharingapple(m, n - 1);
}

void main(){
	int m, n;
	cin >> m >> n;
	cout << sharingapple(m, n) << endl;
	system("pause");
}

放苹果(递归)_第1张图片

你可能感兴趣的:(huawei)