首页 > 其他 > 详细

LintCode Climbing Stairs

时间:2016-08-11 12:51:54      阅读:169      评论:0      收藏:0      [点我收藏+]

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example

Given an example n=3 , 1+1+1=2+1=1+2=3

return 3

For the problem, try to think about it in this way.

Firstly, we define the problem of DP(n) as the ways of approaching to n stairs. 

The problem of DP(n) depends on DP(n-1) and DP(n-2). Then the DP(n) = DP(n-1) + DP(n-2). Because there is two possibilities for DP(n) happen due to the rule that either it is accomplished by step 1 or step 2 stairs before approaching to n.

Initialize the DP(0) =1 and DP(1) = 1.

Solve problem DP(n)

 1 public class Solution {
 2     /**
 3      * @param n: An integer
 4      * @return: An integer
 5      */
 6     public int climbStairs(int n) {
 7         // write your code here
 8         if (n <= 1) {
 9             return 1;
10         }
11         int last = 1, lastlast = 1;
12         int now = 0;
13         for (int i = 1; i < n; i++) {
14             now = last + lastlast;
15             lastlast = last;
16             last = now;
17         }
18         return now;
19     }
20 }

Then this problem is a fibonacci sequence

LintCode Climbing Stairs

原文:http://www.cnblogs.com/ly91417/p/5760499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!