某些业务场景下,我们会用到组合穷举方法,这里整理几个穷举方法
1、不限顺序的数组组合穷举:
<?php//索引位置function getAnswer($amount, $need){if($need == 1){for ($i=1;$i<=$amount;$i++){$rst[] = [$i];}return $rst;}else{$rst = getAnswer($amount-1, $need-1);foreach($rst as $v){for ($i=$v[$need-2]+1;$i<=$amount;$i++){$v[$need-1] = $i;$result[] = $v;}}return $result;}}//通过索引取数组值function getFinallyAnswer($array, $pick){$amount = count($array);$sub = getAnswer($amount, $pick);foreach ($sub as $k => $v){foreach ($v as $per_sub){$rst[$k][] = $array[$per_sub - 1];}}return $rst;}//穷举算法function getSequenceAry($arr){if (count($arr) == 1) {return array($arr);}$arrRet = array();foreach ($arr as $k => $v) {$arr2 = $arr;unset($arr2[$k]);$arrOrderList = getSequenceAry($arr2);foreach ($arrOrderList as $order) {array_unshift($order, $v);$arrRet[] = $order;}}return $arrRet;}echo count(getFinallyAnswer(array(1,2,3,4,5,6,7,8),5));//print_r(getSequenceAry(array(1,2,3,4)));print_r(getAnswer(8,5));