算法问题:字母组合

算法问题:字母组合,第1张

算法问题:字母组合

您要保留数字->字母分配的一般结构是一个或多个数组,类似于:

// 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, // 8 = H or CH or J, 9 = G$numberMap = new Array (    0 => new Array("N"),    1 => new Array("L"),    2 => new Array("T"),    3 => new Array("D"),    4 => new Array("R"),    5 => new Array("V", "F"),    6 => new Array("B", "P"),    7 => new Array("Z"),    8 => new Array("H", "CH", "J"),    9 => new Array("G"),);

然后,一些递归逻辑为我们提供了类似于以下功能:

function GetEncoding($number) {    $ret = new Array();    for ($i = 0; $i < strlen($number); $i++) {        // We're just translating here, nothing special.        // $var + 0 is a cheap way of forcing a variable to be numeric        $ret[] = $numberMap[$number[$i]+0];    }}function PrintEncoding($enc, $string = "") {    // If we're at the end of the line, then print!    if (count($enc) === 0) {        print $string."n";        return;    }    // Otherwise, soldier on through the possible values.    // Grab the next 'letter' and cycle through the possibilities for it.    foreach ($enc[0] as $letter) {        // And call this function again with it!        PrintEncoding(array_slice($enc, 1), $string.$letter);    }}

递归三声欢呼!这将通过以下方式使用:

PrintEncoding(GetEncoding("052384"));

并且,如果您真的希望将其作为数组,请使用输出缓冲并使用“ n”作为拆分字符串进行爆炸。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4909595.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存