2

我需要一个返回所有可能组合的函数,

例如

字符=范围('a','c');

  1. = aaa
  2. = aab
  3. = 阿巴
  4. = abb
  5. = abc
  6. = acb ... n。= cc

(顺序无关紧要)

等等

我懂了

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}

$p = pc_permute(array(0, 1, 2, 3));
var_dump($p);

这里

但我无法弄清楚如何机会/重写它以获得与多个相同元素的所有可能组合。

谢谢, 穆罕默德

4

1 回答 1

1

请使用此功能:

<?php 
$characters = range('a','c');


function get_permutations(array $arr = array()){
    if(count($arr) == 1){
        return array_values($arr);
    }

    $return_array = array();

    foreach($arr as $key => $val){
        $temp_arr = $arr;
        unset($temp_arr[$key]);
        $temp = call_user_func(__FUNCTION__, $temp_arr);
        for($x = 0; $x < count($temp); $x++){
            $temp[$x] = $val.$temp[$x];
        }
        $return_array = array_merge($return_array, $temp);
    }
    return $return_array;
}

var_dump(get_permutations($characters));

输出:

array(6) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "acb"
  [2]=>
  string(3) "bac"
  [3]=>
  string(3) "bca"
  [4]=>
  string(3) "cab"
  [5]=>
  string(3) "cba"
}

编辑:

<?php 
$characters = range('a','h');


function get_permutations(array $arr = array(), $max_length = NULL){
    if(count($arr) == 1 || ($max_length !== NULL && $max_length <= 1)){
        return array_values($arr);
    }

    $return_array = array();

    foreach($arr as $key => $val){
        $temp_arr = $arr;
        unset($temp_arr[$key]);
        $temp = call_user_func(__FUNCTION__, $temp_arr, $max_length !== NULL ? $max_length - 1 : NULL);
        for($x = 0; $x < count($temp); $x++){
            $temp[$x] = $val.$temp[$x];
        }
        $return_array = array_merge($return_array, $temp);
    }
    return $return_array;
}

var_dump(get_permutations($characters, 4));

注意:当心使用a-z范围会导致更长的运行时间甚至导致内存不足错误,所以我用一个小范围进行了测试:)

于 2012-11-06T12:48:30.467 回答