1. 题目说明

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

  1. 输入: [1,2,3]
  2. 输出:
  3. [
  4. [1,2,3],
  5. [1,3,2],
  6. [2,1,3],
  7. [2,3,1],
  8. [3,1,2],
  9. [3,2,1]
  10. ]

2. 解题

<?php
class Solution {
    public $res = [];
    public function permute($nums, $tpArr = []) {
        if (!$nums) return;

        if (count($tpArr) == count($nums)) {
            $this->res[] = $tpArr;
            return;
        }

        foreach ($nums as $v) {
            if (isset($tpArr[$v])) {
                continue;
            }
            $tpArr[$v] = $v;
            $this->permute2($nums, $tpArr);
            array_pop($tpArr);
        }
        return;
    }
}

$nums = [1,2,3];
$cls = new Solution();
$cls->permute($nums);
array_walk($cls->res, function (&$v){
    $v = implode(',', $v);
});
echo implode("\n", $cls->res);