标签:log pre sel else key function unset public 字符串排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
<?php
class Test{
/**
* arr 元素数组,
* m 从arr 中选择的元素个数
* isRepeat arr中的元素是否可以重复(默认重复)
* b 中间变量
* n 等于第一次调用时的 m
* res 存放结果
*/
public static function combine($arr, $m, $isRepeat = 0, $b = [], $n = 0, $res = []) {
!$n && $n = $m;
if($m == 1) {
foreach($arr as $item)
//拼接中间变量到数组中去
$res[] = array_merge($b, [$item]);
} else {
foreach($arr as $key => $item) {
$b[$n - $m] = $item;
$tmp = $arr;
if(!$isRepeat) unset($tmp[$key]);// 如果不可重复
$res = self::combine($tmp, $m-1, $isRepeat, $b, $n, $res);
}
}
return $res;
}
}
var_dump(Test::combine([‘a‘,‘b‘, ‘c‘], 3));
标签:log pre sel else key function unset public 字符串排列
原文地址:http://www.cnblogs.com/qqblog/p/6518746.html