排列组合

公司的要做一个优惠券的功能,里面用到了排列组合的算法,这里针对不同的需求的一些PHP的代码。

给出的数字 1,2,3

需求一

需要的结构:

1, 12, 13, 123, 2, 23, 3

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
function arrange ($arr, $temp_string, &$collect = [], $i = 0) use (&$func)
{
if ($temp_string != "")
$collect []= $temp_string.',';

for ($i; $i<count($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (count($arrcopy) > 0) {
arrange($arrcopy, $temp_string ."," . $elem[0], $collect, $i);
} else {
$collect []= $temp_string. "," . $elem[0].',';
}
}
};

使用

1
2
arrange([1,2,3], '', $result);
var_dump($result);

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~