递归思想,leetcode17. Letter Combinations of a Phone Number和46. Permutations

本文探讨了电话号码对应的字母组合算法及整数的全排列算法,通过具体的Python实现,展示了如何生成所有可能的字母组合以及整数的所有排列方式。提供了详细的代码解析,适合算法初学者和面试准备者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Letter Combinations of a Phone Number
题目
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.



Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路

字符串集合不断作笛卡尔积。
例如:求“23”时,先放digits中的第一位“2”,就是[“a”,“b”,“c”]了,然后是digits中的下一位3,再将[“a”,“b”,“c”]与剩余数字串“3”对应的字符列表[“d”,“e”,“f”]做笛卡尔积,于是就得到了[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]。

class Solution(object):
    def addDigit(self,digit,ans):
        tmp = []
        for element in digit:
            if len(ans) == 0:
                tmp.append(element)
            for s in ans:
                tmp.append(s + element)
        return tmp    
    
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
    
        ans = []
        dic = {'0':'','1':'*','2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        for element in digits:
            ans = self.addDigit(dic[element],ans)
        return ans

46. Permutations

题目
Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
思路

一个数的全排列是其本身,然后再其余的一组,不断变换位置
for里a的输出,
[1, 2]
[1]
[1, 3]
[1]
[]
[2, 1]
[2]
[2, 3]
[2]
[]
[3, 1]
[3]
[3, 2]
[3]
[]

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        res=[]
        def perm(res,a,num,n,max):
            if n==max:
                res.append(a)
            for i in range(0,len(num)):
                perm(res,a+[num[i]],num[:i]+num[i+1:],n+1,max)
        perm(res,[],nums,0,len(nums))
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值