A brief discussion on sample code sharing of permutations and combinations in PHP

黄舟
Release: 2023-03-06 17:40:02
Original
1331 people have browsed it

The following editor will bring you a brief discussion on the permutations and combinations of PHP (such as inputting a, b, c and outputting all their combinations). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. 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; } }
Copy after login

The above is the detailed content of A brief discussion on sample code sharing of permutations and combinations in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!