leetcode17 電話號碼的字母組合
阿新 • • 發佈:2019-01-12
給定一個僅包含數字 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