需求:php
有一個數組 ['a', 'b', 'c', 'cd']數組
須要從數組中取出任意 m 個不重複的元素,列出全部的可能性(也不須要出現重複的組合例如['a', 'b' ,'c'] 和 ['a', 'c', 'b'])。blog
能夠使用遞歸來完成:遞歸
<?php function getCombinationToString($arr, $m) { if ($m == 1) { return $arr; } $result = []; $tmpArr = $arr; unset($tmpArr[0]); for($i = 0; $i < count($arr); $i++) { $s = $arr[$i]; $ret = getCombinationToString(array_values($tmpArr), ($m - 1), $result); foreach($ret as $row) { $val = $s . ',' . $row; $val = explode(',', $val); sort($val); $val = implode(',', $val); if(! in_array($s, explode(',', $row)) && ! in_array($val, $result)) { $result[] = $val; } } } return $result; } $arr = ['a', 'b', 'c', 'cd']; $t = getCombinationToString($arr, 3); echo '<pre>';print_r($t);
若是容許包含重複的組合,把 line:17 的條件註釋便可。 get
輸出:io
Array ( [0] => a,b,c [1] => a,b,cd [2] => a,c,cd [3] => b,c,cd )
方法2、function
<?php $words = array('a', 'b', 'c'); $num = count($words); $total = pow(2, $num); for ($i = 0; $i < $total; $i++) { for ($j = 0; $j < $num; $j++) { if (pow(2, $j) & $i) echo $words[$j] . ' '; } echo '<br />'; }