1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- /*
- * This file is part of the Jiannei/lumen-api-starter.
- *
- * (c) Jiannei <longjian.huang@foxmail.com>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace App\Services;
- class CombinationService
- {
- public static function combination($arr, $num)
- {
- $r = array();
- $n = count($arr);
- if ($num <= 0 || $num > $n) {
- return $r;
- }
- for ($i = 0; $i < $n; $i++) {
- $t = array($arr[$i]);
- if ($num == 1) {
- $r[] = $t;
- } else {
- $b = array_slice($arr, $i + 1);
- $c = self::combination($b, $num - 1);
- foreach ($c as $v) {
- $r[] = array_merge($t, $v);
- }
- }
- }
- return $r;
- }
- public static function combinationALL($array, $level = -1, &$list = [])
- {
- for ($i = 0; $i < count($array); $i++) {
- if ($level < 0) {
- //第一级直接输出对应数字
- $list[][] = $array[$i];
- } else {
- $values = $array[$i];
- //根据等级组装前几位
- for ($k = 0; $k < $level; $k++) {
- $values .= '+' . $array[$i + $k + 1];
- }
- $j = 0;
- //循环拼合最后一位
- for ($n = ($i + $level + 1); $n < count($array); $n++) {
- $j++;
- $first = $values; // 组合上几位
- $first .= '+' . $array[$n];
- $list[] = str2arr($first, '+');
- }
- //到最后一位结束递归
- if ($j == 1) {
- break;
- }
- }
- }
- //长度大于等级+2停止递归
- if (($level + 2) < count($array)) {
- self::combinationALL($array, $level + 1, $list);
- }
- return $list;
- }
- }
|