Java O(1) solution


  • 0
    Z

    Its a Fibonacci sequence,so we can just use the formula.Besides,recursive is Time Limit Exceeded,and using a array is also a good way.

    return (int)(1/Math.sqrt(5)*(Math.pow((1+Math.sqrt(5))/2,n+1)-Math.pow((1-Math.sqrt(5))/2,n+1)));


  • 0
    Z
    This post is deleted!

  • 0

    We can use recursion + dynamic programming. That solves the TLE error for plain recursion.

    public class Solution {
        public int climb(int[] results, int n) {
            if(n == 0) return 1;
            if(n > 0) {
                if(results[n] != 0) {
                    return results[n];
                }
                results[n] = climb(results, n-1) + climb(results, n-2);
                return results[n];
            }
            return 0;
    
        }
        public int climbStairs(int n) {
            int[] results = new int[n+1];
            return climb(results, n);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.