算法刷题Day 38 动态规划理论基础+斐波那契数+爬楼梯

Day 38 动态规划

理论基础

动态规划的解题步骤:

  1. 确定dp数组(dp table)以及下标的含义
  2. 确定递推公式
  3. dp数组如何初始化
  4. 确定遍历顺序
  5. 举例推导dp数组

斐波那契数

很基础

class Solution {
public:
    int fib(int n) {
        int a = 0, b = 1;
        while (n--)
        {
            b = a + b;
            a = b - a;
        }

        return a;
    }
};

爬楼梯

class Solution {
public:
    int climbStairs(int n) {
        long long step1 = 1, step2 = 1; // 应该声明为long long,防止溢出

        while (n--)
        {
            step2 = step1 + step2;
            step1 = step2 - step1;
        }

        return step1;
    }
};

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