北大筆試——放蘋果

題目描述 把M個一樣的蘋果放在N個一樣的盤子裏,容許有的盤子空着不放,問共有多少種不一樣的分法?java

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

思路:ui

N個盤子放M個分兩個互斥的狀況
①沒有盤子放0個,每一個盤子至少1個,等於N個盤子放M-N個
②有盤子放0個,等於N-1個盤子放M個code

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);
	}
}
相關文章
相關標籤/搜索