Last active
December 19, 2016 09:59
-
-
Save coder-liyang/c92a4ae6080417e6fc7b4af537cbb01e to your computer and use it in GitHub Desktop.
排列&&组合算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * 排列的总个数 | |
| * @param int $n | |
| * @param int $m | |
| * @return int | |
| */ | |
| function a($n, $m){ | |
| if($n < $m) return false; | |
| $num = 1; | |
| for($i=0; $i<$m; $i++){ | |
| $num = $num * ($n-$i); | |
| } | |
| return $num; | |
| } | |
| //echo a(5,3); | |
| /** | |
| * 组合的总个数 | |
| * @param int $n | |
| * @param int $m | |
| * @return int | |
| */ | |
| function c($n, $m){ | |
| if($n < $m) return false; | |
| return a($n,$m)/a($m,$m); | |
| } | |
| //echo c(5,3) | |
| /** | |
| * 排列枚举算法 | |
| * @param $arr | |
| * @param int $len | |
| * @param string $str | |
| */ | |
| function arrangement($arr, $len=0, $str="") { | |
| global $res; | |
| $arr_len = count($arr); | |
| if($len == 0){ | |
| $res[] = $str; | |
| }else{ | |
| for($i=0; $i<$arr_len; $i++){ | |
| $tmp = array_shift($arr); | |
| arrangement($arr, $len-1, $str."\t".$tmp); | |
| array_push($arr, $tmp); | |
| } | |
| } | |
| } | |
| $arr = array(1,2,3,4,5,6,7); | |
| $num = 2; | |
| $res = array(); | |
| arrangement($arr, $num); | |
| //var_dump($res); | |
| /** | |
| * 组合枚举算法 | |
| * @param $arr | |
| * @param int $len | |
| * @param string $str | |
| */ | |
| function combination($arr, $len=0, $str="") { | |
| global $res; | |
| $arr_len = count($arr); | |
| if($len == 0){ | |
| $res[] = $str; | |
| }else{ | |
| for($i=0; $i<$arr_len-$len+1; $i++){ | |
| $tmp = array_shift($arr); | |
| combination($arr, $len-1, $str."\t".$tmp); | |
| } | |
| } | |
| } | |
| $arr = array(1,2,3,4,5,6,7); | |
| $num = 2; | |
| $res = array(); | |
| combination($arr, $num); | |
| //var_dump($res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment