Leetcode[17][46] python实现
2018-12-23 16:38
579 查看
Leetcode[17][46] python实现
Leetcode (17) 电话号码的字母组合
题目
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
分析
利用递归的思想,字典存储数字与字母的关系,字符串的加法。
代码
class Solution(object): def letterCombinations(self, digits): # 28ms """ :type digits: str :rtype: List[str] """ l = [] # 先初始化存储结果的数组 num = {'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']} if len(digits)==0: return[] if len(digits)==1: return list(num[digits]) else: next = self.letterCombinations(digits[1:]) for i in next: for j in num[digits[0]]: l.append(j+i) return l
Leetcode (46) 全排列
题目
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
分析
调用itertools库中的permutations函数,再使用list进行类型转换
代码
from itertools import permutations class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return list(permutations(nums))
相关文章推荐
- LeetCode 64. Minimum Path Sum---Python实现
- LeetCode 56 Merge Intervals(Python实现及详解)
- leetcode练习(35,38) python实现
- LeetCode 3. Longest Substring Without Repeating Characters---Python实现
- leetcode 【 Reorder List 】python 实现
- [leetcode]47. Permutations II,python实现
- leetcode的python实现 刷题笔记9:回文数 暴力解法和进阶算法
- LeetCode- 16. 最接近的三数之和 (Medium)python和c++实现
- python实现 LeetCode37——Sudoku Solver
- leetcode 【 Insertion Sort List 】 python 实现
- LeetCode 91 Decode Ways (Python详解及实现)
- LeetCode 93 Restore IP Addresses(Python详解及实现)
- leetcode 【 Pascal's Triangle 】python 实现
- LeetCode 71 Simplify Path(Python详解及实现)
- 【leetcode】Integer to Roman--python实现
- LeetCode 98 Validate Binary Search Tree(Python详解及实现)
- [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】
- LeetCode39/40/22/77/17/401/78/51/46/47/79 11道回溯题(Backtracking)
- LeetCode 30. Substring with Concatenation of All Words----Python实现
- LeetCode 60 Permutation Sequence (Python实现及详解)