The bullshit sword refers to the offer- frog up the stairs problem:
Problem description: A frog can take 1 or 2 steps at a time. How many ways can the frog jump to n steps?
Problem analysis:
There are two jumping methods in the first step: a> Assuming that the first jump is step 1, then the remaining steps are n-1 steps, and the jumping method is f(n-1);
b> Assuming that the first jump is 2 steps, then the rest are n-2 steps, and the jump method is f(n-2);
Then it can be known from a and b that the total jump method f(n)=f(n-1)+f(n-2);
And because when n=1, f(1)=1; when n=2, f(2)=2; we can get:
| 1,(n=1)
f(n)=| 2,(n=2)
| f(n-1)+f(n-2) (n>2, n is an integer)
It can be found that this is a Fibonacci sequence;
code show as below:
import java.util.Scanner; /** * The sword refers to the offer- * Frog up the stairs problem: * A frog can go up 1 or 2 steps at a time. Find how many ways the frog can jump up to n steps. * @author Jiacheng * */ public class Frogwstj { public static void main(String[] args) { Frogwstj frog=new Frogwstj(); Scanner scanner=new Scanner(System.in); while(true){ int count=frog.upperStage(scanner.nextInt()); System.out.println("Total: "+count+" methods"); } } /** * recursive calculation * @param n number of steps * @return the total way to go up the stairs */ private int upperStage(int n) { if(n==1){ return 1; } if(n==2){ return 2; } int sum=upperStage(n-1)+upperStage(n-2); return sum; } }