北大笔试——放苹果

题目描述 把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?

http://www.nowcoder.com/practice/a96b78e871c347bbb8cadf7bea0ee862?tpId=40&tqId=21395&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

思路:

N个盘子放M个分两个互斥的情况
①没有盘子放0个,每个盘子至少1个,等于N个盘子放M-N个
②有盘子放0个,等于N-1个盘子放M个

package com.tonyluis.oj;

import java.util.*;

public class Main {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			int apple = in.nextInt();
			int cup = in.nextInt();
			System.out.println(calc(apple, cup));
		}
	}

	static int calc(int apple, int cup) {
		if (apple < 0)
			return 0;
		else if (apple <= 1 || cup == 1)
			return 1;
		return calc(apple, cup - 1) + calc(apple - cup, cup);
	}
}

 

posted @ 2016-09-02 21:04  TonyLuis  阅读(231)  评论(0编辑  收藏  举报