You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP生成n位数字的所有唯一全排列并存入数组

你现有的实现依赖str_shuffle随机生成排列,无法保证覆盖所有可能的结果,字符数量越多漏排的概率越高,不属于可靠的全排列实现。

你可以通过回溯算法实现稳定的全排列生成,参考代码如下:

function getFullPermutations($str) {
    $chars = str_split($str);
    $len = count($chars);
    $result = [];
    
    $permute = function($startIndex) use (&$permute, &$chars, $len, &$result) {
        // 递归到最后一位时,当前字符组合就是一个有效排列
        if ($startIndex === $len - 1) {
            $result[] = implode('', $chars);
            return;
        }
        for ($i = $startIndex; $i < $len; $i++) {
            // 交换当前位与后续位的字符
            [$chars[$startIndex], $chars[$i]] = [$chars[$i], $chars[$startIndex]];
            // 递归处理下一位
            $permute($startIndex + 1);
            // 回溯,换回位置保证后续排列生成正确
            [$chars[$startIndex], $chars[$i]] = [$chars[$i], $chars[$startIndex]];
        }
    };
    
    $permute(0);
    // 自动去重,适配输入存在重复字符的场景
    return array_unique($result);
}

// 调用示例
$num = "123";
$allPermutations = getFullPermutations($num);
print_r($allPermutations);

如果你使用的PHP版本低于7.1,不支持数组解构赋值,可以将交换代码替换为传统临时变量写法:

$temp = $chars[$startIndex];
$chars[$startIndex] = $chars[$i];
$chars[$i] = $temp;

运行上述代码后输出结果如下,完全符合你的预期:

Array
(
    [0] => 123
    [1] => 132
    [2] => 213
    [3] => 231
    [4] => 321
    [5] => 312
)

内容的提问来源于stack exchange,提问作者Wilf。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:27:03