17. Letter Combinations of a Phone Number

栏目: PHP · 发布时间: 7年前

内容简介:之前把Leetcode上关于二叉树整理出了14道经典题目,如果面试写不出来,那麻烦你手写一个红黑树吧

2 0 1 9 -6-3   期一  

之前把Leetcode上关于二叉树整理出了14道经典题目,如果面试写不出来,那麻烦你手写一个红黑树吧 17. Letter Combinations of a Phone Number

Leetcode二叉树经典题目集合解析

17. Letter Combinations of a Phone Number

让我们根据电话号码的数字,组合所有情况的字符串,题目给的是23,对应着九种组合。

思想就是把给定的数字一位位拿出来,获取它指定的字符串集,然后和其他位上的数字字符串集和一位位进行组合。

/**
     * @param String $digits
     * @return String[]
     */
    function letterCombinations($digits) {    
         return $this->helper($digits,"");      
    }
      
    function helper($digits,$char)
    {
        $array = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
        $res=[];
        $strings=$array[$digits[0]];
        $len=strlen($strings);
        for($i=0;$i<$len;$i++){
            $val=$strings[$i];
            if(strlen($digits)==1){  //如果给定只有一个数字的话
                array_push($res,$char.$val);
            }else{
                $moreStrings=$this->helper(substr($digits,1),$char.$val);
                foreach($moreStrings as $more){
                    array_push($res,$more);
                }
            }
        }
        return $res;
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rationality for Mortals

Rationality for Mortals

Gerd Gigerenzer / Oxford University Press, USA / 2008-05-02 / USD 65.00

Gerd Gigerenzer's influential work examines the rationality of individuals not from the perspective of logic or probability, but from the point of view of adaptation to the real world of human behavio......一起来看看 《Rationality for Mortals》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具