力扣刷题——电话号码的字母组合

题目: https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

1.哈希映射 逐层遍历

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
    let res = []
    if(digits.length === 0) return []
    let map = {
        2: 'abc',
        3: 'def',
        4: 'ghi',
        5: 'jkl',
        6: 'mno',
        7: 'pqrs',
        8: 'tuv',
        9: 'wxyz'
    }
    for(let num of digits){
        let chars = map[num]
        if(res.length > 0){
            let temp = []
            for(let old of res){
                for(let char of chars){
                    temp.push(old + char)
                }
            }
            res = temp
        }else {
            res.push(...chars)
        }
    }
    return res
};

2.递归

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
    let res = []
    if(digits.length === 0) return []
    let map = {
        2: 'abc',
        3: 'def',
        4: 'ghi',
        5: 'jkl',
        6: 'mno',
        7: 'pqrs',
        8: 'tuv',
        9: 'wxyz'
    }
    function generate(i, str){
        let len = digits.length
        if(i === len){
            res.push(str)
            return 
        }
        let chars = map[digits[i]]
        for(let j = 0; j < chars.length; j++ ){
            generate(i+1, str + chars[j])
        } 
    }
    generate(0, '')
    return res
};

你可能感兴趣的:(刷题)