代码随想录算法训练营第四十一天|509. 斐波那契数 ● 70. 爬楼梯 ● 746. 使用最小花费爬楼梯

509. 斐波那契数

int fib(int n){
    if (n <= 1) return n;
    int* pb = (int*)malloc(sizeof(int) * (n + 1));
    pb[0] = 0;
    pb[1] = 1;
    for (int i=2; i<=n; i++)
    {
        pb[i] = pb[i - 1] + pb[i - 2];
    }
    return pb[n];
}
int fib(int n){
    if (n <= 1) return n;
    int dp[2];
    dp[0] = 0;
    dp[1] = 1;
    for (int i=2; i<=n; i++)
    {
        int sum = dp[0] + dp[1];
        dp[0] = dp[1];
        dp[1] = sum;
        
    }
    return dp[1];
}

70. 爬楼梯

int climbStairs(int n){
    if (n <= 1) return n;
    int* pb = (int*)malloc(sizeof(int) * (n + 1));
    pb[0] = 1;
    pb[1] = 1;
    for (int i=2; i<=n; i++)
    {
        pb[i] = pb[i - 1] + pb[i - 2];
    }
    return pb[n];
}

746. 使用最小花费爬楼梯

int minCostClimbingStairs(int* cost, int costSize){
    int dp[costSize + 1];
    dp[0] = dp[1] = 0;
    for (int i = 2; i <= costSize; i++) {
        dp[i] = fmin(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]);
    }
    return dp[costSize];
}

你可能感兴趣的:(代码随想录算法,算法,数据结构,c语言,leetcode)