Java dp solutions, recursion & iteration


  • 0
    M
    public class Solution {
        public int climbStairs(int n) {
            if(n<=2) return n;
            int[] dp = new int[n+1];
            dp[1] = 1;
            dp[2] = 2;
            // return recursion(n, dp);
            return iteration(n, dp);
        }
        private int recursion(int n, int[] dp){
            if(dp[n]!=0) return dp[n];
            int sum = recursion(n-1, dp);
            sum += recursion(n-2, dp);
            dp[n] = sum;
            return sum;
        }
        
        private int iteration(int n, int[] dp){
            for(int i=3; i<=n; i++){
                dp[i] = dp[i-2] + dp[i-1];
            }
            return dp[n];
        }
    }
    
    

Log in to reply
 

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