php全组合代码实现

php全组合代码实现

$a = ['a', 'b', 'c'];
$b = get_combinations($a);
echo json_encode($b);

function get_combinations($str, &$comb = [])
{
    if (count($str) > 1) {
        $str_first = array_shift($str);
        $comb_temp = get_combinations($str, $comb);
        $comb[] = [$str_first];
        $oreach ($comb_temp as $k => $v) {
            $item = $v;
            $item[] = $str_first;
                $comb[] = $item;
        }
    } else {
        $comb[] = $str;
    }

    return $comb;
 }

-------------------------
输出结果:
[
	["c"],
	["b"],
	["c","b"],
	["a"],
	["c","a"],
	["b","a"],
	["c","b","a"]
] 

你可能感兴趣的:(数据结构)