快樂的LeetCode --- 17. 電話號碼的字母組合

題目描述:

給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
在這裏插入圖片描述
示例:

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

解題思路1:

代碼1目前只能實現針對兩個字符及以下的情況


代碼1:

class Solution(object):
    def keys(self, str_count):
        if str_count == '2':
            return "abc"
        if str_count == '3':
            return "def"
        if str_count == '4':
            return "ghi"
        if str_count == '5':
            return "jkl"
        if str_count == '6':
            return "mno"
        if str_count == '7':
            return "pqrs"
        if str_count == '8':
            return "tuv"
        if str_count == '9':
            return "wxyz"

    def letterCombinations(self, digits):
        num = []   # num中存放的是字符串分離開來的單個字符,對比官方代碼發現,該功能是可以省略
        number = len(digits)
        res = []   # res中存放的是組合之後的結果
        if number == 1:
            num.append(self.keys(digits[0][len(digits[0])-1]))
            for j in range(len(num[0])):
                res.append(num[0][j])
            return res

        for i in range(number):
            num.append(self.keys(digits[i]))

        for i in range(len(num)-1):
            k = 0
            while k < len(num[i]):
                for j in range(len(num[i+1])):
                    res.append(num[i][k]+num[i+1][j])
                k += 1
        return res

解題思路2: 回溯

來源於:LeetCode官方題解
  回溯是一種通過窮舉所有可能情況來找到所有解的算法。如果一個候選解最後被發現並不是可行解,回溯算法會捨棄它,並在前面的一些步驟做出一些修改,並重新嘗試找到可行解。

  給出如下回溯函數 backtrack(combination, next_digits) ,它將一個目前已經產生的組合 combination 和接下來準備要輸入的數字 next_digits 作爲參數。

如果沒有更多的數字需要被輸入,那意味着當前的組合已經產生好了。
如果還有數字需要被輸入:
遍歷下一個數字所對應的所有映射的字母。
將當前的字母添加到組合最後,也就是 combination = combination + letter
重複這個過程,輸入剩下的數字: backtrack(combination + letter, next_digits[1:])
在這裏插入圖片描述


代碼2:

class Solution:
    def letterCombinations(self, digits):
        phone = {'2': ['a', 'b', 'c'],
                 '3': ['d', 'e', 'f'],
                 '4': ['g', 'h', 'i'],
                 '5': ['j', 'k', 'l'],
                 '6': ['m', 'n', 'o'],
                 '7': ['p', 'q', 'r', 's'],
                 '8': ['t', 'u', 'v'],
                 '9': ['w', 'x', 'y', 'z']}

        def backtrack(combination, next_digits):
            # if there is no more digits to check
            if len(next_digits) == 0:
                # the combination is done
                output.append(combination)
            # if there are still digits to check
            else:
                # iterate over all letters which map
                # the next available digit
                for letter in phone[next_digits[0]]:
                    # append the current letter to the combination
                    # and proceed to the next digits
                    backtrack(combination + letter, next_digits[1:])

        output = []
        if digits:
            backtrack("", digits)
        return output

題目來源:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章