給定一個僅包含數字2-9的字符串,返回所有它能表示的字母組合。
給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例:
輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
說明:盡管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作權歸領扣網絡所有。商業(yè)轉載請聯系官方授權,非商業(yè)轉載請注明出處。
更多更好答案:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode/
這道題我是用了笛卡爾積運算的,在此做個記錄
代碼如下:
class Solution {
? ? /**
? ? * @param String $digits
? ? * @return String[]
? ? * array_shift 刪除第一個元素,并返回刪除的元素的值(其實就是返回第一個元素的值)
? ? *?array_merge_recursive 把兩個數組合并為一個數組,如果有鍵名相同值不同的,就會將值合并到一個數組中,共同指向這個鍵
? ? */
? ? function letterCombinations($digits) {
? ? ? ? if(!$digits){
? ? ? ? ? ? return [];
? ? ? ? }
? ? ? ? $arr=[
????????????0=>[],
????????????1=>[],
? ? ? ? ? ? 2=>['a','b','c'],
? ? ? ? ? ? 3=>['d','e','f'],
? ? ? ? ? ? 4=>['g','h','i'],
? ? ? ? ? ? 5=>['j','k','l'],
? ? ? ? ? ? 6=>['m','n','o'],
? ? ? ? ? ? 7=>['p','q','r','s'],
? ? ? ? ? ? 8=>['t','u','v'],
? ? ? ? ? ? 9=>['w','x','y','z'],
? ? ? ? ];
? ? ? ? $numarr=str_split($digits);
? ? ? ? $newdigits=[]; //構造出需要運算的數組
? ? ? ? foreach($numarr as $v){
? ? ? ? ? ? $newdigits[]=$arr[$v];
? ? ? ? }
? ? ? ? $arr1=[];
? ? ? ? $result=array_shift($newdigits); //刪除并獲取數組($newdigits) ?中第一個元素的值
? ? ? ? while ($arr2=array_shift($newdigits)){ //在新數組($?newdigits)中刪除并獲取第一個元素的值
? ? ? ? ? ? $arr1=$result;
? ? ? ? ? ? $result=[];?
? ? ? ? ? ? foreach ($arr1 as $value) {
? ? ? ? ? ? ? ? foreach ($arr2 as $value1) {
? ? ? ? ? ? ? ? ? ? $result[]=$value.''.$value1;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return $result;
? ? }
}