Home  >  Article  >  Backend Development  >  Detailed explanation of permutations and combinations in PHP

Detailed explanation of permutations and combinations in PHP

墨辰丷
墨辰丷Original
2018-05-24 17:11:202919browse

The following editor will bring you a brief discussion on the permutations and combinations of PHP-. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

The examples are as follows:

 11 b,c,a
2 c,b,a ===> 21 c,a,b
3 a,b,c ===> 31 a,c,b

**/
function zuhe($arr,$begin){
  if(!is_array($arr)) return ;
  $N = count($arr);
  if($begin == $N-1 || $begin >$N || $begin <0) return ;
  if($begin == 0){
    print_r($arr);//输出原始数据
    echo '
'; } //循环将初始值与第i个值交换后进行组合 for($i = $begin;$i < $N;$i++){ $t = $arr[$begin]; $arr[$begin] = $arr[$i]; $arr[$i] = $t; if($i!==$begin){//i==begin时的数已经输出过 print_r($arr); echo '
'; } zuhe($arr,$begin+1); $t = $arr[$begin]; $arr[$begin] = $arr[$i]; $arr[$i] = $t; } } $arr = array('a','b','c','d'); //zuhe($arr,0); /*分治法——直接插入 初始时从0个元素开始,输出初始序列,为组合的一个序列 当在来一个元素时只需将该元素放在该元素之前的元素组的不同的位置即组成了不同的排列 如已有元素组为a,b.新元素为c,把c分别与a,b进行交换即可(a,c,b);(c,b,a),在现有的排列上在新增元素 重复执行以上步骤 */ function zuhe2($arr,$begin){ if($begin==0) { print_r($arr); echo "
"; //zuhe2($arr,$begin+1); } if($begin >= count($arr)) return ; zuhe2($arr,$begin+1);//begin时的排列上一次已产生,直接新增元素 for($i = $begin-1;$i>=0;$i--){ $t = $arr[$begin]; $arr[$begin] = $arr[$i]; $arr[$i] = $t; print_r($arr); echo "
"; zuhe2($arr,$begin +1); $t = $arr[$begin]; $arr[$begin] = $arr[$i]; $arr[$i] = $t; } }

The above is The entire content of this article is hoped to be helpful to everyone's study.


Related recommendations:

Single permutation and combination implemented by PHP Detailed explanation of algorithm examples

PHP is simplePermutation and combinationAlgorithm example sharing

##JS fullPermutation and combinationAlgorithm implementation method

The above is the detailed content of Detailed explanation of permutations and combinations in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn