您的位置:首页 > 编程语言 > Python开发

Leetcode[17][46] python实现

2018-12-23 16:38 579 查看

Leetcode[17][46] python实现

  • Leetcode (46) 全排列
  • 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))
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: