Home >Backend Development >PHP Tutorial > 一个排列组合算法有关问题 抛砖引玉一上

一个排列组合算法有关问题 抛砖引玉一上

WBOY
WBOYOriginal
2016-06-13 12:59:071054browse

一个排列组合算法问题 抛砖引玉一下
中学时候都学过 排列组合 1 2 3 4 5 6可以组成720个不同的字符串
这里写了一个粗糙的实现方法 例为 1- 6
希望哪个高手可以指点一二 
$j=0;
for($i=123456;$i $box=array();

$ge =$i%10;
if($ge>6 || $ge==0){
continue;
}
$box[]=$ge;
$shi = intval($i/10)%10;
if($shi>6 || $shi ==0){
continue;
}
$box[]=$shi;
$bai = intval($i/100)%10;
if($bai>6 || $bai ==0){
continue;
}
$box[]=$bai;
$qian = intval($i/1000)%10;
if($qian>6 || $qian ==0){
continue;
}
$box[]=$qian;
$wan = intval($i/10000)%10;
if($wan>6 || $wan ==0){
continue;
}
$box[]=$wan;
$shiwan = intval($i/100000);
if($shiwan>6 || $shiwan ==0){
continue;
}
$box[]=$shiwan;
//echo count(array_unique($box));
//echo '
';
//var_dump(array_unique($box));
//echo '
';
if(count(array_unique($box))!=6){
continue;
}

if($j%10==0){
echo "
";
}
$j++;
echo ' ',$i,' ';
}
echo "
";
echo "一共{$j}个";
------解决方案--------------------

$a = perm(array(1,2,3,4,5,6));<br />
echo count($a);<br />
//print_r($a);<br />
<br />
function perm($list, $k=0, $m=0) {     <br />
  if(! $m) $m = count($list) - 1; <br />
  $r = array();    <br />
  if($k >= $m) {          <br />
    $r[] = join('', $list);         <br />
  }else {         <br />
    for($i = $k; $i <= $m; $i++) {             <br />
      list($list[$k], $list[$i]) = array($list[$i], $list[$k]);<br />
      $r = array_merge($r, perm($list, $k + 1, $m));             <br />
      list($list[$k], $list[$i]) = array($list[$i], $list[$k]);<br />
    }<br />
  }<br />
  return $r;<br />
}

720

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