Stairs - Dynamic Programming

Suppose you are climbing stairs. N order you need to reach.

Every time you can climb one or two steps. How many different ways can climb to the roof of it?

Note: Given n is a positive integer.

Example 1:

Input: 2 
Output: 2 
explanation: There are two methods can climb the roof. 
1 .   1 order + 1 -order
 2 .   2 Order

Example 2:

Input: 3 
Output: 3 
Explanation: There are three methods can climb to the roof. 
1 .   1 order + 1 order + 1 -order
 2 .   1 order + 2 order
 . 3 .   2 stage + 1 -order

 

Solution one: Dynamic Programming

Do not speak like the idea, look at the time value of n is changing, what law do? With many possibilities record result

  1. When n = 0, result = 0;
  2. When n = 1, result = 1;
  3. When n = 2, result = 2;
  4. When n = 3, result = 3;
  5. When n = 4, result = 5 ......

We found that by following the above rules:

thought

Let's talk about ideas, not difficult to find, this problem can be broken down into several sub-questions include the optimal substructure that its optimal solution can be effectively build sub-optimal solution to the problem from which you can use dynamic programming to to solve this problem.

I-th order can be obtained from the following two methods:

  1. In the first - after (i 1) to climb Order Order
  2. In the first - after (i 2) Order to climb two stage

Therefore, the total number of method reaches the i-th order is the number of the first and - - (2 i) A method of order (i. 1) and.

Order DP [i] represents the number of ways to reach the i-th order:

dp[ i ] = dp[i - 1] + dp[i - 2]

Code

climbStairs FUNC (_ n-: Int) -> Int { 
        Guard n- > 0  the else { return  0 }
     IF n-== . 1 {
         return  . 1 
    } 
    var DP: [Int] = [Int] () 
    dp.append ( 0 ) // The first element, when n = 0, absent manner climb upstairs 
    dp.append ( . 1 ) // second element, when n = 1, 1 ways 
    dp.append ( 2 ) // third element , when n = 2, 2 ways 
    for I in  . 3 .. <n-+ . 1 {
        dp.append (DP [I-. 1] + DP [I - 2 ]) // a = append as with the assignment 
    } 
    return DP [n-] 
    }

result

The above is the idea of ​​dynamic programming to do, there are other ideas to make this topic in the future, will be updated with the latest ideas and code (because at this stage focus on dynamic programming solution).

Guess you like

Origin www.cnblogs.com/guohai-stronger/p/11796576.html