php回溯算法计算组合总和的实例代码

admin3年前PHP教程32

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明

所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。

实例

输入:

candidates = [10,1,2,7,6,1,5], target = 8,

所求解集为:

[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]]

解题思路

直接参考回溯算法团灭排列/组合/子集问题。

代码


class Solution {
    /** * @param Integer[] $candidates * @param Integer $target * @return Integer[][] */
    public $res = [];
    function combinationSum2($candidates, $target) {
        sort($candidates);   // 排序
        $this->dfs([], $candidates, $target, 0);
        return $this->res;
    }
    function dfs($array, $candidates, $target, $start) {
        if ($target < 0) return;
        if ($target === 0) {
            $this->res[] = $array;
            return;
        }
        $count = count($candidates);
        for ($i = $start; $i < $count; $i++) {
            if ($i !== $start && $candidates[$i] === $candidates[$i - 1]) continue;
            $array[] = $candidates[$i];
            $this->dfs($array, $candidates, $target - $candidates[$i], $i + 1);//数字不能重复使用,需要+1
            array_pop($array);
    }}

实例扩展:


<?php
/*
 * k = 2x + y + 1/2z
 取值范围
 * 0 <= x <= 1/2k
 * 0 <= y <= k
 * 0 <= z < = 2k
 * x,y,z最大值 2k
 */
$daMi = 100;
$result = array();
function isOk($t,$daMi,$result)
{/*{{{*/
 $total = 0;
 $hash = array();
 $hash[1] = 2;
 $hash[2] = 1;
 $hash[3] = 0.5;
 for($i=1;$i<=$t;$i++)
 {
 $total += $result[$i] * $hash[$i];
 }
 if( $total <= $daMi)
 {
 return true;
 }
 return false;
}/*}}}*/
function backtrack($t,$daMi,$result)
{/*{{{*/
 //递归出口
 if($t > 3)
 {
 //输出最优解
 if($daMi == (2 * $result[1] + $result[2] + 0.5 * $result[3]))
 {
  echo "最优解,大米:${daMi},大牛:$result[1],中牛: $result[2],小牛:$result[3]\n";
 }
 return;
 }
 for($i = 0;$i <= 2 * $daMi;$i++)
 {
 $result[$t] = $i;
 //剪枝
 if(isOk($t,$daMi,$result))
 {
  backtrack($t+1,$daMi,$result);
 }
 $result[$t] = 0;
 }
}/*}}}*/
backtrack(1,$daMi,$result);
?>

到此这篇关于php回溯算法计算组合总和的实例代码的文章就介绍到这了,更多相关php回溯算法计算组合总和的方法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

免责声明:本文内容来自用户上传并发布,站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。请核实广告和内容真实性,谨慎使用。

相关文章

laravel csrf验证总结

laravel csrf验证总结前言问题:laravel 在web路由下无论是表单提交啊 还是ajax请求啊 只要是请求方式不满足 ['HEAD', 'GET', &#...

高防服务器配置指标有什么方面?怎么衡量好坏?国内电信高防服务器性能如何?

谈到产品配置,不少人已早有耳闻,像大家平常购买手机、电脑等电子类产品时,都会关注到这个产品的配置如何,使用的时候流不流畅,会不会出现延迟大顿等。同样的,在大家购买高防服务器的时候,依旧会参考这些指标来...

PHP Class self 与 static 异同与使用详解

对于大多数 PHPer 来说,self 与 static 两个 PHP 关键词都不算陌生。我们学会通过self::xxxx这种方式来调用当前类的静态属性和方法。而 static 呢?想必很多人只知道它...

租韩国服务器多少钱一个月

租韩国服务器多少钱一个月?租用韩国服务器的价格是由多种因素共同影响的,以下是一些主要的因素:服务器性能:服务器的性能决定了它的承载能力和处理速度,通常来说,性能越高的服务器租用费用就越贵。网络带宽:网...

租用美国高防服务器需要考虑哪些因素

选择租用美国高防服务器时,需要考虑以下几个因素:1.防御能力:高防服务器的主要目的是提供强大的防御能力,能够对DDoS等攻击方式进行有效防范。因此,在选择高防服务器时,需要考虑其防御能力是否足够强大,...

解决启动php-fpm后访问不到php文件的办法

问题场景:linux系统nginx服务器安装好了fpm的php7在nginx的web目录下新建了index.php文件,内容为phpinfo()函数。(如果是源码安装,位置一般为 /usr/local...