面试题14:剪绳子

 

Leetcode

<?php
header("content-type:text/html;charset=utf-8");
/*
 * 剪绳子 把一根绳子剪成多段,并且使得每段的长度乘积最大。 P96
 */

//动态规划
function integerBreak1($length){
    if($length < 2){
        return 0;
    }
    if($length == 2){
        return 1;
    }

    if($length == 3){
        return 2;
    }
    $products = array();
    $products[0] = 0;
    $products[1] = 1;
    $products[2] = 2;
    $products[3] = 3;
    for($i=4;$i<=$length;$i++){
        $max = 0;
        for($j = 1;$j<$i;$j++){
            $product = $products[$j] * $products[$i-$j];
            if($max < $product){
                $max = $product;
            }
            $products[$i] = $max;
        }
    }
    return $products[$length];
}

//贪心算法
function integerBreak2($length){
    if($length < 2){
        return 0;
    }
    if($length == 2){
        return 1;
    }

    if($length == 3){
        return 2;
    }
    $timesOf3 = floor($length / 3);
    if($length - $timesOf3 * 3 == 1){
        $timesOf3--;
        $timesOf2 = ($length - $timesOf3 * 3)/2;
    }
    return (pow(3,$timesOf3) * pow(2,$timesOf2));

}

echo integerBreak1(10);
echo integerBreak2(10);

 

转载于:https://www.cnblogs.com/xlzfdddd/p/10162784.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值