Recursion is very intuitive to solve some problems, but you should pay attention to the depth of recursion when using recursion. If the depth is too deep, Stack Overflow may occur. The following example shows how to use it.
Question: Super stair Problem description has a total of M-level stairs. At the beginning, you are at the first level. If you can only cross the upper or second level at a time, how many steps should you go to level M? Input data first contains an integer N, indicating the number of test instances, followed by N rows of data, each row contains an integer m (1 <= m <= 40 ), the level of the stair. Output for each test instance, please output the number of samples input223sample output12 different steps to solve the problem: First of all, we need to find the rule for this type of questions, you can try to write out the case where M is relatively small, and then find the rule from it. Example: m steps 12 1-23 1-3 (two steps from 1) 1-2-3 (one step from 2) 4 1-2-4 (two levels from 2) 1-2-3-4 1-3-4 (one level from 3) 5 1-2-3-5 1-3-5 (two steps from 3) 1-2-3-4-5 1-2-4-5 1-3-4-5 (level from 4) 6 1-2-4-6 1-2-3-4-6 1-3-4-6 (two steps from 4) 1-2-3-5-6 1-3-5-6 1-2-3-4-5-6 1-2-4-5-6 1-3- 4-5-6 (from 5 to 5)... All the steps of N N-2 layer can reach N layer at two levels, and the steps of n-1 layer can reach N layer at one level, which can be expressed as F (N ), then f (n) = f (n-1) + f (n-2), N> 4 so that we can use recursive calculation. The reference code is as follows:/** super stair */public static int test7 (int n) {Switch (n) {Case 1: Return 0; Case 2: return 1; Case 3: return 2; default: Return test7 (n-1) + test7 (n-2) ;}} for this question, the use of recursion is not fast, and the recursion is too deep, it will overflow, you can use loops for processing. refer to the following code:/** super stair */public static int test7 (int n) {int [] result = new int [40]; result [0] = 0; Result [1] = 1; Result [2] = 2; for (INT I = 3; I <n; I ++) {result [I] = Result [I-1] + result [I-2];} return result [n-1];}
Additional reading:
ACM simulation questions (1)-High Precision
ACM simulation question details (2) -- simple number theory
ACM simulation questions (3) -- number theory (continued)
ACM (4) -- Recursion
ACM (5) -- sorting
ACM (6) -- Stack
ACM (7)-compression and encoding
ACM (8)-Encryption
ACM (9)-others
Li xucheng csdn blog: http://blog.csdn.net/javaeeteacher
Csdn student base camp: http://student.csdn.net/space.php? Uid = 1, 124362
If you like my article, add me as a friend: http://student.csdn.net/invite.php? U= 124362 & C = 7be8ba2b6f3b6cc5