Title: Suppose you need to enter a room, but the room is upstairs, you need to walk through the n steps to go upstairs, if you can walk 1, 2 or 3 steps at a time, you can calculate how many plans you have to go through all the steps into the room?
The idea of solving a problem: Defining a state function f (n) is used to indicate that if there is a total number of plans to go to the nth step, then f (n) =f (n-1) +f (n-2) +f (n-3). When N=1, there is only one program, when the n=2 there are two kindsof programs (A; 2) When n=3, there are 4 kinds of programs (1,1,1; ; 2,1; 3), and so on.
Specific algorithms (Java edition)
1 /**2 * Calculate n steps a total of how many of the way3 */4 Public classStep {5 6 Public Static intWalkintNint[] stepways) {7 if(n <= 0)8 return0;9 intCount = 0;Ten for(inti = 0; i < stepways.length; i++) { One if(n = =Stepways[i]) { ACount + = 1; -}Else { -Count + = Walk (N-Stepways[i], stepways); the } - } - returncount; - } + - Public Static voidMain (string[] args) { + int[] Stepways =New int[] {3, 1, 2}; A intn = 10; at System.out.println (Walk (n, stepways)); - } - -}
If there is any problem, can communicate together!
Dynamic planning--up stairs