某些业务场景下,我们会用到组合穷举方法,这里整理几个穷举方法

1、不限顺序的数组组合穷举:

  1. <?php
  2. //索引位置
  3. function getAnswer($amount, $need){
  4. if($need == 1){
  5. for ($i=1;$i<=$amount;$i++){
  6. $rst[] = [$i];
  7. }
  8. return $rst;
  9. }else{
  10. $rst = getAnswer($amount-1, $need-1);
  11. foreach($rst as $v){
  12. for ($i=$v[$need-2]+1;$i<=$amount;$i++){
  13. $v[$need-1] = $i;
  14. $result[] = $v;
  15. }
  16. }
  17. return $result;
  18. }
  19. }
  20. //通过索引取数组值
  21. function getFinallyAnswer($array, $pick){
  22. $amount = count($array);
  23. $sub = getAnswer($amount, $pick);
  24. foreach ($sub as $k => $v){
  25. foreach ($v as $per_sub){
  26. $rst[$k][] = $array[$per_sub - 1];
  27. }
  28. }
  29. return $rst;
  30. }
  31. //穷举算法
  32. function getSequenceAry($arr)
  33. {
  34. if (count($arr) == 1) {
  35. return array($arr);
  36. }
  37. $arrRet = array();
  38. foreach ($arr as $k => $v) {
  39. $arr2 = $arr;
  40. unset($arr2[$k]);
  41. $arrOrderList = getSequenceAry($arr2);
  42. foreach ($arrOrderList as $order) {
  43. array_unshift($order, $v);
  44. $arrRet[] = $order;
  45. }
  46. }
  47. return $arrRet;
  48. }
  49. echo count(getFinallyAnswer(array(1,2,3,4,5,6,7,8),5));
  50. //print_r(getSequenceAry(array(1,2,3,4)));
  51. print_r(getAnswer(8,5));