[Daily Blue Bridge] 4. The real question of the first three years of provincial Java group "39th step"

Hello, I am the little gray ape, a programmer who can write bugs!

Welcome everyone to pay attention to my column " Daily Blue Bridge ". The main function of this column is to share with you the real questions of the Blue Bridge Cup provincial competitions and finals in recent years, analyze the algorithm ideas, data structures and other content that exist in it, and help you learn To more knowledge and technology!

Subject Title: Step 39

Xiao Ming had just watched the movie "Step 39". When he left the cinema, he counted the number of steps in front of the auditorium, which happened to be 39. Standing in front of the steps, he suddenly thought of another question:

If I can only take one or two steps at each step, first take the left foot, then alternate left and right, and the last step is to take the right foot, that is to say, I have to take an even number of steps, then after the 39 steps, how many different are there? Where is the law?

Please take advantage of the computer to help Xiao Ming find the answer,

Required to submit is an integer

Note: Do not submit the answering process or other supporting text

Problem-solving ideas :

This question is solved using a recursive method. The idea is the same as the Fibonacci sequence, but it is the reverse application of the Fibonacci sequence.

We have two ways to take each step, that is, one step or two steps, so that the number of steps we have left will be reduced by 1 or 2, and our number of steps will increase by 1.

So we only need to judge whether the number of remaining steps is 0. If the number of remaining steps is 0, it means that you have reached the top level. At this time, you can judge whether the number of steps is even. If it meets the requirements, add 1 to the variable of the number of recording methods.

Answer source code:

package 一三年省赛真题;

public class Year2013_t4 {

	public static void main(String[] args) {
		f(39,0);
		System.out.println("方法有:" + answers);
	}
	
	static int answers = 0;		//定义符合要求的方法个数
	
	/**
	 * @param n 剩余的台阶数
	 * @param step 已经走过的步数
	 * */
	public static void f(int n,int step) {
		if (n<0) {
			return;
		}
		//如果剩余的台阶数为0说明已经走完,并且步数为偶数时,符合要求,
		if (n==0&&step%2==0) {
			answers++;	//方法加1
			return;
		}
		f(n-1, step+1);	//下一步是一个台阶
		f(n-2, step+1);	//下一步是两个台阶
	}

}

Sample output:

There are deficiencies or improvements, and I hope my friends will leave a message and learn together!

Interested friends can follow the column!

Little Grey Ape will accompany you to make progress together!

Guess you like

Origin blog.csdn.net/weixin_44985880/article/details/112585318