标签:inpu .com 划算 ++ mic style 空间 code 优化
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
Solution1:递归
class Solution { public int climbStairs(int n) { if(n==1){ return 1; } else if(n==2){ return 2; } else{ return climbStairs(n-2) + climbStairs(n-1); } } }
但是运行显示 Time limited exceed.
网上大佬说是因为递归的效率太低,会产生很多分支,所以放弃使用递归。
Solution2:
class Solution { public int climbStairs(int n) { if(n<=1){ return 1; } else{ int[] dp = new int[n]; dp[0] = 1; dp[1] = 2; for(int i = 2; i < n; i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n-1]; } } }
这个方法使用了Dynamic Programming提高效率。来自Grandyang大佬。
solution3
“我们可以对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值,首先将a+b的值赋给b,然后a赋值为原来的b,所以应该赋值为b-a即可。这样就模拟了上面累加的过程,而不用存储所有的值,参见代码如下:”
我去这是什么神仙方法,
public class Solution { public int climbStairs(int n) { int a = 1, b = 1; while (n-- > 0) { b += a; a = b - a; } return a; } }
附递归和动态规划算法题目详解:
http://www.cnblogs.com/DarrenChan/p/8734203.html#_label1
标签:inpu .com 划算 ++ mic style 空间 code 优化
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10201202.html