LeetCode题解:Climbing Stairs
来源:互联网 发布:危机公关 知乎 编辑:程序博客网 时间:2024/05/22 07:56
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层楼梯的办法数
解决思路:
动态规划,状态转移方程:f(n) = f(n - 1) + f(n - 2) (n > 2),f(0) = 0,f(1) = 1,f(2) = 2.
斐波那契,随便选个n做例子算办法数就会发现和斐波那契数列是一样的(状态转移方程就一样),所以可以直接利用这一点实现,不需要O(n)
的空间来完成动态规划
代码:
动态规划:
public class Solution { public int climbStairs(int n) { if(n == 0 || n == 1 || n == 2){ return n; } int[] mem = new int[n]; mem[0] = 1; mem[1] = 2; for(int i = 2; i < n; i++){ mem[i] = mem[i-1] + mem[i-2]; } return mem[n-1]; }}
斐波那契:
public class Solution { public int climbStairs(int n) { if(n < 0){ return 0; } if(n < 3){ return n; } int result = 0; int oneStep = 1; int twoStep = 1; for(int i = 2;i <= n;i++){ result = oneStep + twoStep; twoStep = oneStep; oneStep = result; } return result; }}
0 0
- LeetCode题解:Climbing Stairs
- LeetCode题解:Climbing Stairs
- LeetCode题解:Climbing Stairs
- LeetCode 题解(226) : Climbing Stairs
- Leetcode题解 70. Climbing Stairs
- LeetCode 70 Climbing Stairs题解
- leetcode题解-70. Climbing Stairs
- LeetCode70. Climbing Stairs题解
- LeetCode 70. Climbing Stairs 题解 —— Java
- 【动态规划】Leetcode编程题解:70. Climbing Stairs
- LeetCode: Climbing Stairs
- LeetCode: Climbing Stairs
- [LeetCode]Climbing Stairs
- LeetCode Climbing Stairs
- [Leetcode] Climbing Stairs
- Leetcode: Climbing stairs
- LeetCode Climbing Stairs
- [LeetCode] Climbing Stairs
- hdu5047 Sawtooth(推导+java大数)
- Spring MVC入门案例(2)
- 宽度决定高度
- Spring事务配置的五种方式
- Struts DynaActionForm example
- LeetCode题解:Climbing Stairs
- 对select()参数fdset的完整理解 http://blog.csdn.net/maray/article/details/8285775
- Redis管道(Pipelining)操作
- ZOJ 1649 Rescue
- android handler 内存泄露
- Session_Flow
- jquery使用cdn加载问题
- iOS多线程之NSoperation和GCD的比较
- COSMOS&SCOPE---微软内部的大数据平台(1)