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

如何用PHP生成给定三位数的所有不重复排列组合?

PHP生成三位数的不重复排列组合实现

方案一:递归生成时避免重复(高效)

这种方法在递归过程中就跳过已使用的重复字符,从根源减少重复排列的生成,适合存在重复数字的场景:

function getUniquePermutations($inputStr) {
    $charArray = str_split($inputStr);
    $result = [];

    // 递归生成排列的内部函数
    $generatePerms = function($current, $remaining) use (&$generatePerms, &$result) {
        if (empty($remaining)) {
            $result[] = $current;
            return;
        }

        $usedChars = [];
        foreach ($remaining as $index => $char) {
            // 跳过当前层级已用过的字符,避免重复分支
            if (in_array($char, $usedChars)) continue;
            $usedChars[] = $char;

            $newRemaining = $remaining;
            array_splice($newRemaining, $index, 1);
            $generatePerms($current . $char, $newRemaining);
        }
    };

    $generatePerms('', $charArray);
    return $result;
}

// 测试无重复数字的情况
$test1 = "123";
echo implode(',', getUniquePermutations($test1)) . PHP_EOL;
// 输出:123,132,213,231,312,321

// 测试含重复数字的情况
$test2 = "001";
echo implode(',', getUniquePermutations($test2)) . PHP_EOL;
// 输出:001,010,100

方案二:全排列后去重(简洁)

如果对性能要求不高,也可以先生成所有可能的排列,再通过array_unique去除重复项,代码更简洁:

function getPermutationsWithDedupe($inputStr) {
    $charArray = str_split($inputStr);
    $result = [];

    $generatePerms = function($current, $remaining) use (&$generatePerms, &$result) {
        if (empty($remaining)) {
            $result[] = $current;
            return;
        }

        foreach ($remaining as $index => $char) {
            $newRemaining = $remaining;
            array_splice($newRemaining, $index, 1);
            $generatePerms($current . $char, $newRemaining);
        }
    };

    $generatePerms('', $charArray);
    return array_unique($result);
}

// 测试
echo implode(',', getPermutationsWithDedupe("001")) . PHP_EOL;
// 输出:001,010,100

关键说明

  • 两种方案都保留了前导零,符合输入包含0的需求。
  • 方案一在递归时就过滤重复字符,生成的结果直接无重复,效率更高;方案二先全量生成再去重,代码更短但重复字符较多时会产生冗余计算。

内容的提问来源于stack exchange,提问作者naveen R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:05:32