Dynamic planning--up stairs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.