一道排列组合的算法题

给你一个40斤的西瓜,给3个人分,有多少种分法?我用PHP实现的,代码如下

$aa = range(1,40);
$bb = array();
foreach($aa as $k=>$val){
    foreach($aa as $v){
        foreach($aa as $vl){
            $sum = $val+$v+$vl;
            if($sum == 40){
                $bb[$k][0] = $val;
                $bb[$k][1] = $v;
                $bb[$k][2] = $vl;
            }
        }
    }
}
echo '<pre>';
print_r($bb);
exit;

结果:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 38
            [2] => 1
        )

    [1] => Array
        (
            [0] => 2
            [1] => 37
            [2] => 1
        )

    [2] => Array
        (
            [0] => 3
            [1] => 36
            [2] => 1
        )

    [3] => Array
        (
            [0] => 4
            [1] => 35
            [2] => 1
        )

 ........

posted @ 2015-06-05 10:39  北京流浪儿  阅读(237)  评论(0编辑  收藏  举报