Leetcode -17. Letter Combinations of a Phone Number
阿新 • • 發佈:2018-11-07
這個問題我最開始的想的是使用樹的結構去做,之後用python實現的時候是使用了幾個for迴圈:
class Solution: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ dic = {'2':'abc', '3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} ans = [] i = 0 """ 讀取輸入的數字,如果試一次輸入,直接將第一個數字對應的字母分別新增進入ans """ for s in digits: if ans == []: for st in dic[s]: ans.append(st) i += 1 """ 讀取已存在的letter combinations """ else: l = len(ans) """ 對letter combinations分別新增新的letter 並 生成新的 letter combinations """ for j in range(l): for st1 in dic[s]: ans.append(ans[j]+st1) """ 因為是直接將新的letter combinations新增進入ans,所以需要刪除舊的letter combinations """ ans = ans[j+1:] i += 1 return ans
在discuss區中,排名第一的演算法(one line python):
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): if '' == digits: return [] kvmaps = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, ['']) # ['']為初始引數,即acc, digits為可迴圈引數:x = [], digit = _ for _ in digits
語法
reduce() 函式語法:
reduce(function, iterable[, initializer])
引數
- function -- 函式,有兩個引數
- iterable -- 可迭代物件
- initializer -- 可選,初始引數