Home >php教程 >php手册 >PHP全组合算法

PHP全组合算法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 19:38:121061browse

一个简单的递归方法求全组合 无 ?php//组合1$a[] = array('book1', 'book2');//组合2$a[] = array('1', '2', '3');//组合3$a[] = array('z', 'y', 'x');//组合4$a[] = array('sd', 'sds', 'sdsd');$output=combination($a,0);echo "pre";print_r($output);//

一个简单的递归方法求全组合
<?php
//组合1
$a[] = array(&#39;book1&#39;, &#39;book2&#39;);
//组合2
$a[] = array(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;);
//组合3
$a[] = array(&#39;z&#39;, &#39;y&#39;, &#39;x&#39;);
//组合4
$a[] = array(&#39;sd&#39;, &#39;sds&#39;, &#39;sdsd&#39;);
$output=combination($a,0);
echo "<pre class="brush:php;toolbar:false">";
print_r($output);

//其它组合根据需要直接先生成一个array
//注意键值必须为数字




function combination(&$input_arr,$index){
	if($index>=sizeof($input_arr)-1){
		return $input_arr[$index];
	}else{
		$low_b=combination($input_arr,$index+1);
		$b=array();
		foreach($input_arr[$index] as $ch)
			foreach($low_b as $low_arr)
				$b[]=array_merge(array($ch),is_array($low_arr)? $low_arr: array($low_arr));
		return $b;
	}
}
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