From today on, I have practiced an algorithm question every day. Today is the first question-put apple.
Put M identical apples on N identical dishes, and some are allowed to leave them empty. How many different methods are there? (Expressed in K) 5, 1, 1, and 1, 5, 1 are the same method.
The first line is the number of test data to be input t (0 <=t <= 20 ). The following two integers, M and N, are separated by spaces. 1 <= M, N <= 10.
Output the corresponding K in one row for each group of input data M and N.
Input:
1 7 3 (1 indicates entering a group of data)
Output: 8
Input:
2 8 4 7 3 (2 indicates entering two groups of data)
Output:
15
8
If f (m, n) is set to m apples and n plates are used as the number of plates, n is discussed first,
When n> m: there must be n-m plates that are always empty, removing them will not affect the number of Apple placement methods. That is, if (n> m) f (m, n) = f (m, m)
When n <= m: Different la s can be divided into two types:
1. At least one plate is empty, that is, f (m, n) = f (m, n-1 );
2. All the dishes have apples, which is equivalent to removing an apple from each plate without affecting the number of different placement methods, that is, f (m, n) = f (m-n, n ).
However, the total number of Apple placement methods is equal to the sum of the two, that is, f (m, n) = f (m, n-1) + f (m-n, n)
Description of recursive exit conditions:
When n = 1, all the apples must be placed on one plate, so 1 is returned;
When there is no apple, it is defined as a release method;
The first n of the two recursion paths will gradually decrease and eventually reach the exit n = 1;
The second m will gradually decrease, because when n> m, we will return f (m, m), so it will eventually reach the exit m = 0.
Import java. util. secret; public class TheApple {public static void main (String args []) {int t, m, n; random in = new random (System. in); t = in. nextInt () + 1; while (t = t-1)> 0) {m = in. nextInt (); n = in. nextInt (); System. out. println (fun (m, n) ;}} static int fun (int m, int n) // There are several methods to put m apples on n plates {if (m = 0 | n = 1) // because we always let m> = n to solve the problem, so m-n> = 0, so let m end at 0. If it is changed to m = 1, return 1; // The m-n = 0 may occur, and thus the correct solution is not obtained. if (n> m) return fun (m, m); elsereturn fun (m, n-1) + fun (m-n, n );}}
Reference: http://www.cnblogs.com/celia01/archive/2012/02/19/2358673.html
Author: jason0539
Weibo:
Blog: (For details, refer to the source)