※北京大学 放苹果(java)

题目描述
把 M 个同样的苹果放在 N 个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?
注意:5、1、1 和 1、5、1 是同一种分法,即顺序无关。
输入描述:
输入包含多组数据。

每组数据包含两个正整数 m和n(1≤m, n≤20)。
输出描述:
对应每组数据,输出一个整数k,表示有k种不同的分法。
示例1
输入
复制
7 3
输出
复制
8
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.* ;
public class Main
{
	static int count = 0;
	public static void main(String[] args) {
		try 
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String str;
			while((str = br.readLine()) != null) {
				String[] lines = str.split(" ");
				int m = Integer.parseInt(lines[0]);
				int n = Integer.parseInt(lines[1]);
				System.out.println(getCount(m, n));
			}
		} catch(IOException e) {
			e.printStackTrace();	
		}
	}
    //组合,递归
	public static int getCount(int m, int n) {	
		if(m == 0 || n == 1) {
			return 1;
		}
        if(n > m) return getCount(m, m);//有的空盘子是肯定没用的
        else {
            return getCount(m-n, n) + getCount(m, n-1);//分成两种情况,有空盘子和没有空盘子
        }
	}
}

发布了252 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104291151