美文网首页
背包问题,使用回溯法

背包问题,使用回溯法

作者: lifefruity | 来源:发表于2021-02-01 21:41 被阅读0次
    <?php 
    
    //背包0-1问题=>3,4,6,8KG的物品,背包最大10KG,需要求出组合
    //这么想,这个不管什么结果,肯定是全排列的前N个值就是了
    function func($selected, $able){
        if(array_sum($selected) >= 10){
            echo implode('', $selected)."<br>";
            return;
        }
        
        for($i = 0; $i < count($able); $i++){
            //step 1. 可选解【放入】到已选集合中
            $let = $able[$i];
            if(in_array($let, $selected)){
                continue;
            }
            $selected[] = $let;
    
            //step 2. 进入下一个阶段
            func($selected, $able);
            
            //var_dump($selected);exit;
            //step 3.回溯
            array_pop($selected);
        }
        
    }
    
    func([], [3,4,6,8]);
    
    

    相关文章

      网友评论

          本文标题:背包问题,使用回溯法

          本文链接:https://www.haomeiwen.com/subject/thgstltx.html