You are climbing a stair case. It takes n steps to reach to the top.code
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?递归
时间 O(1.618^N) 空间 O(N)it
这题几乎就是求解斐波那契数列。最简单的方法就是递归。但重复计算时间复杂度高。io
public class Solution { public int climbStairs(int n) { if(n==1 || n==0) return 1; else return climbStairs(n-1) + climbStairs(n-2); } }
时间 O(N) 空间 O(N)class
将以前计算过的结果存下来,节省了一些时间。cli
public class Solution { public int climbStairs(int n) { if(n==0) return 0; int[] dp = new int[n+1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i <= n; i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n]; } }
时间 O(N) 空间 O(1)方法
实际上咱们求n的时候只须要n-1和n-2的值,因此能够减小一些空间啊。im
public class Solution { public int climbStairs(int n) { int[] f = new int[]{0,1,2}; if(n < 3) return f[n]; for(int i = 2; i < n; i++){ f[0] = f[1]; f[1] = f[2]; f[2] = f[0] + f[1]; } return f[2]; } }
时间 O(logN) 空间 O(1)top