组合生成算法

给定一个数组:A、B、C、D,输出长度为N的组合,返回所有的组合的方式

<?php

/**
 * 组合:数据集$list,组合的个数:$num
 * @param $list
 * @param $m
 * @return []
 */
function arrangement($list, $num) {
    $res = [];
    $count = count($list);
    if ($num <= 0 || $num > $count) {
        return $res;
    }
    for ($i=0; $i<$count; $i++) {
        $_list = $list;
        $tmp = array_splice($_list, $i, 1);
        if ($num == 1) {
            $res[] = $tmp;
        } else {
            $temp = arrangement($_list, $num-1);
            foreach ($temp as $v) {
                $res[] = array_merge($tmp, $v);
            }
        }
    }
    return $res;
}

$list = ['A', 'C', 'E', 'G'];
print_r( arrangement($list , 4) );

猜你喜欢

转载自blog.csdn.net/a_jie_2016_05/article/details/89314052