重学爬梯子动态规划的解题思路

文章目录

  • 一、递归
  • 二、记忆化递归
  • 三、动态规划
  • 四、滚动数组的动态规划

一、递归

public class Solution {
    public int ClimbStairs(int n) {
        if(n<=3)return n;
        return ClimbStairs(n-1)+ClimbStairs(n-2);
    }
}

二、记忆化递归

public class Solution 
{
    public int ClimbStairs(int n) 
    {
        int[] memo = new int[n+1];
        return ClimbStairsMemo(n,memo);
    }
    public int ClimbStairsMemo(int n,int[] memo) 
    {
        if(n<=3)return n;
        if(memo[n]>0)return memo[n];
        else
        memo[n] = ClimbStairsMemo(n-1,memo) + ClimbStairsMemo(n-2,memo);
        return memo[n];
    }
}

三、动态规划

public class Solution 
{
    public int ClimbStairs(int n) 
    {
        if (n <= 3) 
        {
            return n;
        }
        int[] dp = new int[n+1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) 
        {
            dp[i] = dp[i-1]+dp[i+1];
        }
        return dp[n];
    }
}

四、滚动数组的动态规划

public class Solution 
{
    public int ClimbStairs(int n) 
    {
        if (n <= 3) 
        {
            return n;
        }
        int f1 = 1, f2 = 2;
        for (int i = 3; i <= n; i++) 
        {
            int temp = f1 + f2;
            f1 = f2;
            f2 = temp;
        }
        return f2;
    }
}

你可能感兴趣的:(LeetCode,#,动态规划,动态规划,算法,leetcode)