2012-09-28 53 views
0

可能重複:
PHP: How to get all possible combinations of 1D array?
Generate all possible combinations using a set of strings 如何列出並計算字符串中所有可能的組合?

$s = 'A,B,C'; 

給定一組字符串,你怎麼計算,它可能有 AAA BBB CCC ABC ACB BC A 等?

+0

@andrewsi我很無能上使用什麼PHP函數。我嘗試過'foreach'並且隨機選擇了一次,但是如何刪除重複並在沒有更多選擇時停止。 – IMB

+1

不要隨機,按順序進行。 – moonwave99

+0

使用['explode()'](http://php.net/manual/en/function.explode.php)將字符串轉換爲數組並參考該類型。 – NullUserException

回答

0

在C++是:

do{ 
cout << s << endl; 
}while(next_permutation(s,s+s.size()); 

所以只要經過所有排列。

0

在數組中找到或寫入一個包含遞歸循環的函數。這應該會返回一個包含所有可能組合的數組。

0
$s = explode($s,",") 


function recursion($string, $depth, $maxdepth, $s) 
{ 
    if($depth == $maxdepth) 
     echo $string 
    else 
    { 
     for($i = 0;$i < sizeof($s); $i++) 
     { 
     recursion($string+$s[$i], $depth+1, $maxdepth, $s) 
     } 
    } 
} 

recursion("",0, sizeof($s), $s) 

當然你可以把$ MAXDEPTH和$全局變量從參數列表中排除他們

相關問題