leetcode 70:Climbing Stairs

原创 2015年07月09日 01:37:17

题目:
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?
分析:
考察动态规划,用户上楼梯,每次可迈1步或2步,现有n阶的楼梯,问有多少种方式到达最高的楼梯。定义状态为“到达i阶楼梯有d[i]种方式”;状态转移方程为:d[i]=d[n-2]+d[n-1];因为用户最后一次迈步要么先到n-1阶楼梯,再迈1步;要么先到n-2阶楼梯再迈2步。当i=1或2时,d[i]=i.
代码:

public class ClimbingStairs {
    public static int  countWays(int n){
        int[] result=new int[n];
        if(n<1) return 0;

        if(n>0&&n<3)    return n;
        else{
            result[0]=1;
            result[1]=2;
            for(int i=2;i<n;i++){
                result[i]=result[i-1]+result[i-2];
            }
        }
        return result[n-1];
    }
    public static void main(String[] args){
        int n=5;
        int result=countWays(n);
        System.out.println("result:"+result);
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode 70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1...

[LeetCode]70.Climbing Stairs

【题目】 You are climbing a stair case. It takes n steps to reach to the top. Each time you can eithe...

LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)

翻译你正在爬一个楼梯。它需要n步才能到底顶部。每次你可以爬1步或者2两步。那么你有多少种不同的方法爬到顶部呢?原文You are climbing a stair case. It takes n s...
  • NoMasp
  • NoMasp
  • 2016年01月14日 07:12
  • 4273

leetcode之70. Climbing Stairs(C++解法 动态规划思想)

原题: You are climbing a stair case. It takes n steps to reach to the top.Each time you can either cl...

LeetCode【70】Climbing Stairs

根据题目找规律,见下表策略选择          分析:斐波那契数列的变形           1 1 2 3 5 8 ……           本题将第二个数字1换成数字2,形成新的相同...

LeetCode70. Climbing Stairs题解

You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1...
  • lby0910
  • lby0910
  • 2017年05月05日 12:41
  • 184

【LeetCode】No.70 Climbing Stairs

【原题】 Given an array of integers, find two numbers such that they add up to a specific target number...

Leetcode刷题记——70. Climbing Stairs(爬楼梯)

一、题目叙述: You are climbing a stair case. It takes n steps to reach to the top. Each time...

Leetcode_70_Climbing Stairs

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41851705 You are climbing a st...

leetcode解题之70 #Climbing Stairs Java版 (青蛙跳台阶)

leetcode解题之70 #Climbing Stairs Java版 (青蛙跳台阶)
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 70:Climbing Stairs
举报原因:
原因补充:

(最多只允许输入30个字)