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

最小花费爬楼梯

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);
}
全部评论

相关推荐

科大讯飞消费者bg二级研究院 语音算法岗 24k*14
点赞 评论 收藏
转发
2 收藏 评论
分享
牛客网
牛客企业服务