Home  >  Article  >  Backend Development  >  求数字组合算法解决方案

求数字组合算法解决方案

WBOY
WBOYOriginal
2016-06-13 13:47:481111browse

求数字组合算法
假设有4个数字    
    1,2,3,4    
    要求其中三个数字的排列,但不能重复。
    例如组合:123,124,134,234。
    其中   123   的组合和213,312,321,132,231   的组合都是一样的。
    怎么实现?小弟菜鸟,在线等,谢谢!


------解决方案--------------------
上面有错
for($i=1;$i for($j=$i+1;$j for($k=$j+1;$k echo "$i,$j,$k
";

}
}
}

------解决方案--------------------
/**
* 函数 combination
* 功能 m取n的组合函数
* 参数
* $ar 数组,原始数据
* $num 数值,每个组合的元素个数
**/
if(! function_exists( 'combination ')):
function combination($ar, $num) {
$control = range(0, $num-1);
$k = false;
$total = count($ar);
while($control[0] $t = array();
for($i=0; $i $r[] = $t;

for($i=$num-1; $i> =0; $i--) {
$control[$i]++;
for($j=$i; $j if($control[$i] }
}
return $r;
}
endif;

/** 示例 **/
print_r(combination(array(1,2,3,4,5), 3));

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