题目描述:
把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法。
输入
每个用例包含二个整数M和N。0<=m<=10,1<=n<=10。
输入描述:
输入两个int整数
输出描述:
输出结果,int型
思路:
放苹果分为两种情况,一种是有盘子为空,一种是每个盘子上都有苹果。
令(m,n)表示将m个苹果放入n个盘子中的摆放方法总数。
1.假设有一个盘子为空,则(m,n)问题转化为将m个苹果放在n-1个盘子上,即求得(m,n-1)
2.假设所有盘子都装有苹果,则每个盘子上至少有一个苹果,即最多剩下m-n个苹果,问题转化为将m-n个苹果放到n个盘子上
即求(m-n,n)
综上所述:
(m,n)=(m,n-1)+(m-n,n);
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int m = scanner.nextInt();
int n = scanner.nextInt();
if (m < 1 || n > 10)
System.out.println(-1);
else
System.out.println(count(m, n));
}
}
public static int count(int m, int n)
{
/*if (m < 0)
return 0;
if (m == 1 || n == 1)
return 1;
return count(m, n - 1) + count(m - n, n);*/
if (m <= 0)
return 0;
if (m == 1 || n == 1)
return 1;
if (m == n)
return count(m, n - 1) + 1;
return count(m, n - 1) + count(m - n, n);
}
}
动态规划:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int m = scanner.nextInt();
int n = scanner.nextInt();
if (m < 1 || n > 10)
System.out.println(-1);
else
{
int[][] count = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++)
{
count[i][0] = 1;
count[i][1] = 1;
}
for (int i = 0; i <= n; i++)
{
count[0][i] = 1;
count[1][i] = 1;
}
for (int i = 2; i <= m; i++)
{
for (int j = 2; j <= n; j++)
{
if (i >= j)
count[i][j] = count[i][j - 1] + count[i - j][j];
else
count[i][j] = count[i][j - 1];
}
}
System.out.println(count[m][n]);
}
}
}
}