70. Climbing Stairs(爬楼梯)
2018-03-21 19:10
232 查看
一、题意
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?
Note: Given n will be a positive integer.
二、分析和解答
1、爬上n个台阶总共需要的ways = 爬上n-1个台阶总需的ways(再爬一阶) + 爬上n-2个台阶总需的ways(再爬两阶) 。
所以递推式就得到了:f(n) = f(n-1) + f(n-2)。n肯定得大于0的,所以前面的0,1,2必须拿出来单溜!
更简洁一些:
提交后发现,时间超时!从代码可以看到,每一个递归里面有两个子递归,最后导致整个函数的时间复杂度达到了2^n左右。
2、优化
同样,只需要把前面已经得出来的数据记录下来,就节约了大量的资源。
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?
Note: Given n will be a positive integer.
Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
二、分析和解答
1、爬上n个台阶总共需要的ways = 爬上n-1个台阶总需的ways(再爬一阶) + 爬上n-2个台阶总需的ways(再爬两阶) 。
所以递推式就得到了:f(n) = f(n-1) + f(n-2)。n肯定得大于0的,所以前面的0,1,2必须拿出来单溜!
int climb(int n){ if(n == 0) return 0; if(n == 1) return 1; if(n == 2) return 2; return climb(n-1) + climb(n-2); } public int climbStairs(int n) { return climb(n); }
更简洁一些:
public int climbStairs(int n) { if(n == 0) return 0; if(n == 1) return 1; if(n == 2) return 2; return climbStairs(n-1) + climbStairs(n-2); }
提交后发现,时间超时!从代码可以看到,每一个递归里面有两个子递归,最后导致整个函数的时间复杂度达到了2^n左右。
2、优化
同样,只需要把前面已经得出来的数据记录下来,就节约了大量的资源。
public int climbStairs(int n) { if(n == 0) return 0; if(n == 1) return 1; if(n == 2) return 2; int a = 1;//爬1阶所需的ways int b = 2;//爬2阶所需的ways int i = 3; int res = 0;//当前的阶数 while(i <= n){ res = a + b;//爬i-2阶的ways + 爬i-1阶的ways a = b; b = res; i++; } return res; }
相关文章推荐
- [LeetCode]70. Climbing Stairs(求爬楼梯有几种方式)
- Leetcode刷题记——70. Climbing Stairs(爬楼梯)
- 70. Climbing Stairs(爬楼梯)
- Leet Code OJ 70. Climbing Stairs(爬楼梯问题)
- LeetCode OJ-70. Climbing Stairs(爬楼梯问题)
- leetcode_70. Climbing Stairs 爬楼梯,非递归算法
- 70. Climbing Stairs(爬楼梯)
- 70. Climbing Stairs (爬楼梯)
- LeetCode 70. Climbing Stairs(爬楼梯)
- LeetCode --- 70. Climbing Stairs
- leetCode 70.Climbing Stairs (爬楼梯) 解题思路和方法
- LeetCode --- 70. Climbing Stairs
- leetCode 70.Climbing Stairs (爬楼梯) 解题思路和方法
- Leetcode: 70. Climbing Stairs
- Leetcode 70. Climbing Stairs
- lintcode climbing-stairs 爬楼梯 递归 循环
- 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs