Skip to content

Latest commit

 

History

History
96 lines (80 loc) · 2.78 KB

17.md

File metadata and controls

96 lines (80 loc) · 2.78 KB

✏️Leetcode之PHP版题目解析(17. Letter Combinations of a Phone Number)

2019-06-03 吴亲库里 库里的深夜食堂


✏️描述

让我们根据电话号码的数字,组合所有情况的字符串,题目给的是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;
        }
func letterCombinations(digits string) []string {
	cache := make(map[string][]string)
	cache["2"] = []string{"a", "b", "c"}
	cache["3"] = []string{"d", "e", "f"}
	cache["4"] = []string{"g", "h", "i"}
	cache["5"] = []string{"j", "k", "l"}
	cache["6"] = []string{"m", "n", "o"}
	cache["7"] = []string{"p", "q", "r", "s"}
	cache["8"] = []string{"t", "u", "v"}
	cache["9"] = []string{"w", "x", "y", "z"}

	var helper func(cache map[string][]string, remain string) []string

	helper = func(cache map[string][]string, remain string) []string {
		if len(remain) == 0 {
			return []string{}
		}

		if res, ok := cache[remain]; ok {
			return res
		}

		var res []string

		first := helper(cache, remain[0:1])
		other := helper(cache, remain[1:])
		for _, item := range first {
			for _, otherItem := range other {
				res = append(res, item+otherItem)
			}
		}
		return res
	}
	return helper(cache, digits)
}

联系