全排列(PHP)

/**
* 全排列结果集
* @var array
*/
private $fullPermutationArr = [];

/**
* 全排列
* User: Lindsay
* Date: 2018/9/6
* Time: 9:43
* @param $arr
* @param string $str
*/
public function fullPermutation($arr, $str = '')
{
$cnt = count($arr);
if ($cnt == 1) {
array_push($this->fullPermutationArr, $str ? $str . ',' . $arr[0] : $arr[0]);
} else {
for ($i = 0; $i < count($arr); $i++) {
$tmp = $arr[0];
$arr[0] = $arr[$i];
$arr[$i] = $tmp;
$this->fullPermutation(array_slice($arr, 1), $str ? $str . ',' . $arr[0] : $arr[0]);
}
}
}

// 调用

$this->fullPermutation([1, 2, 3, 4]);
$result = $this->fullPermutationArr;
posted @ 2018-10-19 17:14  lindsayYang  阅读(740)  评论(0编辑  收藏  举报