题解 | #最小花费爬楼梯#

最小花费爬楼梯

https://www.nowcoder.com/practice/6fe0302a058a4e4a834ee44af88435c7

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param cost int整型一维数组 
 * @param costLen int cost数组长度
 * @return int整型
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int recost(int* cost, int rellycostLen )
{
    if(rellycostLen == 2)
        return 0;
        //return cost[0];
    if(rellycostLen == 3)
        return (cost[0] < cost[1]) ? cost[0] : cost[1];
    
    int a = 0;
    int b = 0; 
    int c = 0;
    for(int i = 3;i <= rellycostLen;i++)//这种就不会超时
    {
        c = a+cost[i-3] < b+cost[i-2] ? a+cost[i-3] : b+cost[i-2] ;
        a = b;
        b = c;
        
    }
    return c;
    
    //下面这个递归会超时
    //return (recost(cost,rellycostLen-1)+cost[rellycostLen-2] < recost(cost,rellycostLen-2)+cost[rellycostLen-3] ) ?
       // recost(cost,rellycostLen-1)+cost[rellycostLen-2] : recost(cost,rellycostLen-2)+cost[rellycostLen-3];
}

int minCostClimbingStairs(int* cost, int costLen )
{
    // write code here
    if(costLen == 1)
        return 0;
    if(costLen == 2)
        return (cost[0] < cost[1]) ? cost[0] : cost[1];
    
    return recost(cost,costLen+1);
}
全部评论

相关推荐

牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务