Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP计算元素之和_Php_Algorithm - Fatal编程技术网

PHP计算元素之和

PHP计算元素之和,php,algorithm,Php,Algorithm,我在寻找简单的算法,从数组中计算: $condition = array(2, 20, 200); 致: 有人能说出比以下更简单的事情吗: if(!empty($condition)) { $a = 1; $condition_temp = array(); foreach($condition as $c1) {

我在寻找简单的算法,从数组中计算:

 $condition = array(2, 20, 200);
致:

有人能说出比以下更简单的事情吗:

        if(!empty($condition))
        {
            $a = 1;
            $condition_temp = array();              

            foreach($condition as $c1)
            {
                $c2 =array_slice($condition, $a++);
                foreach($c2 as $c3)
                {
                    $condition_temp[] = $c1 + $c3;      
                }
            }

            $condition_temp[] = array_sum($condition);
            $condition = array_merge($condition, $condition_temp);              
        }
结果数组的顺序并不重要。
thx帮助:)

这取决于。。。您可以在
O(n)
中使用更多内存存储子和,也可以在
O(n^2)
中使用更多时间和更少内存。这取决于你有多少个数字以及计算求和的速度。

你想对数组中的整数求和吗?是的,元素之和(2+20,2+200,20+200,200+2,2+20+200)都是唯一的值,每个值是否如你所问的那样仅由0和2组成?我只有2个可能的数组:1,101001000。。。或202002000。。。
        if(!empty($condition))
        {
            $a = 1;
            $condition_temp = array();              

            foreach($condition as $c1)
            {
                $c2 =array_slice($condition, $a++);
                foreach($c2 as $c3)
                {
                    $condition_temp[] = $c1 + $c3;      
                }
            }

            $condition_temp[] = array_sum($condition);
            $condition = array_merge($condition, $condition_temp);              
        }