数据结构学习day6:递归实战

1 回归递归

递归是指程序调用自身的编程技巧。一般思路:写出递归公式(基础部分和递归部分),编写程序。

2 # leetcode # 17. Letter Combinations of a Phone Number

问题如图:

solution demo:

思路:2-9每个数字代表一串字符,需要一个dict,存储每个数字所代表的字符串;递归思路:递归基础部分直接返回,递归部分,遍历迭加。

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        numbdict = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        digits = list(digits)
        if len(digits)==0:return digits
        numblist = [numbdict[each] for each in digits]
        
        bb = []
        def hh(i,char_):
            if len(numblist)<=i:
                bb.append(char_)
                return 
            for each in numblist[i]:
                hh(i+1,char_+each)
        hh(0,'')
        return bb

result:

参考demo:链接1

(做这此题一直都想用递归,但因对递归的理解十分浅薄,调试许久未果。17的递归思路已有,但一直未能实现,这与我对递归调用时会发生的情况,未能一一想到有关,因此导致我在写内函数时一直未能达到效果;忍不住还是去搜索了讨论区的demo,发现了链接1所给的demo,正好如自己所想,仔细看下去不得不惭愧自己的逻辑能力和代码表达能力的匮乏。)

另附一朋友的demo:大概花了几分钟写出来了。。。大抵我望尘莫及:

2 # leetcode # 46. Permutations

solution demo:

class Solution:
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []        
        def hh(list_, nums):
            if nums:
                for i in nums:
                    mm = nums[:]
                    mm.remove(i)
                    hh(list_+[i],mm)
            else:
                result.append(list_)       
        hh([], nums)
        return result

参考链接2

result:

 

 

参考:

链接1:https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/228456/Python-3-Amazing-100-faster-solution

链接2:https://leetcode.com/problems/permutations/discuss/227833/recursive-python-beats-100

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值