leetcode17 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

第一次理解: 输入“234”, 组合可以为2个字母也可以为3个字母。

             思路: 求出所有的2个字母的组合,在2个字母组合的基础上加入第3个

def letterCombinations(digits):
    """
    :type digits: str
    :rtype: List[str]
    """
    # 数字到对应字母集的映射.比如2 对应[a,b,c]
    num2char = {}
    i1 = 2
    num = 97
    while num < 123:
        num2char[i1] = []
        c = 0
        b = 3
        if i1 == 7 or i1 == 9:
            b = b + 1
        while c < b:
            num2char[i1].append(chr(num))
            num = num + 1
            c = c + 1
        i1 = i1 + 1
    nums = []
    for ch in digits:
        nums.append(int(ch))
    result = []
    result1 = []
    for s1 in range(0, len(nums)-1, 1):
        for s2 in range(s1+1, len(nums), 1):
            result.append([s1, s2])
            tmp = []
            for c1 in num2char[nums[s1]]:
                for c2 in num2char[nums[s2]]:
                    tmp.append(c1+c2)
            result1.append(tmp)

    s = 0
    e = len(result)
    while s < e:
        c = 0
        for i in range(s, e, 1):
            l = result[i]
            t = result1[i]
            for j in range(l[-1] + 1, len(nums), 1):
                tmp = []
                l1 = l.copy()
                l1.append(j)
                result.append(l1)
                for f1 in t:
                    for f2 in num2char[nums[j]]:
                        tmp.append(f1+f2)
                result1.append(tmp)
                c = c + 1
        s = e
        e = e + c
    print(result)
    print(len(result))
    print(result1)
    print(len(result1))
letterCombinations("2345")

 

第二次理解: 题意的意思是:输入3个数字,那么输出必须为3个字母的组合。 不能少于3个

python代码:

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if len(digits) == 0:
            return []
        # 数字到对应字母集的映射.比如2 对应[a,b,c]
        num2char = {}
        i1 = 2
        num = 97
        while num < 123:
            num2char[i1] = []
            c = 0
            b = 3
            if i1 == 7 or i1 == 9:
                b = b + 1
            while c < b:
                num2char[i1].append(chr(num))
                num = num + 1
                c = c + 1
            i1 = i1 + 1
        nums = []
        for ch in digits:
            nums.append(int(ch))
        if len(nums) == 1:
            return num2char[nums[0]]
        result = num2char[nums[0]]
        for num in nums[1:]:
            tmp = []
            for c1 in result:
                for c2 in num2char[num]:
                    tmp.append(c1 + c2)
            result = tmp
        return result

 

你可能感兴趣的:(leetcode17 电话号码的字母组合)