17. Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].


17. Letter Combinations of a Phone Number_第1张图片
image.png

思路:

这道题让我们球电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给出一串数字,求出所有肯呢个的组合,类似的题目有全排列问题,combinations问题 subsets子集合等,用递归来解。首先建立一个字典数组来记录每个字母对应的数字。然后还需要一个变量level来记录当前生成的字符串的字符个数,当等于数字长度时就停止遍历,弹出最后一个数,接着往下找可能的情况,代码如下:

var letterCombinations = function(digits) {
        var res=[];
        if(digits.length==0) return res;
        var dict=['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'];
        DFS(digits,0,dict,"",res);
        return res;

        function DFS(digits,level,dict,out,res){
            if(level==digits.length){
                res.push(out);
            }else{
                var str=dict[digits[level]-2];
                for (var i = 0; i < str.length; i++) {
                    out+=str[i];
                    DFS(digits,level+1,dict,out,res);
                    out=out.substr(0,out.length-1);
                }
            }
        }

      };

你可能感兴趣的:(17. Letter Combinations of a Phone Number)