DAY 25 回溯算法part02

216.组合总和III

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        # 在nums中取数
        nums = [i for i in range(1, 10)]
        res = []

        def Backtracking(cur_nums, cur_res, sumn, index):
            """
            cur_nums:当前可选的数字集合
            cur_res:当前的组合结果
            sumn:当前组合结果中的数字和
            index:当前可选数字的起始索引
            """
            # 终止条件
            if sumn == 0 and len(cur_res) == k:
                res.append(cur_res[:])
                return
            elif sumn != 0 and len(cur_res) == k:
                return
            # 遍历当前可选的数字集合
            for i in range(index, len(cur_nums)):  # 使用 cur_nums 而不是 nums
            # 将当前数字加入组合结果
                cur_res.append(cur_nums[i])  # 使用 cur_nums 而不是 nums
                Backtracking(cur_nums, cur_res, sumn - cur_nums[i], i + 1)  # 传递 sumn - cur_nums[i]
                # 回溯 撤销最后一个数字
                cur_res.pop()

        Backtracking(nums, [], n, 0)  # 使用 nums 而不是 cur_nums
        return res


17.电话号码的字母组合

回溯

这部分代码不太好想

对 对应数字中的字母集合遍历
for letter in phone[nextdigit[0]]:
BackTracking(conbination+letter,nextdigit[1:])

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:return []
        phone = {'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']}
        res = []
        def BackTracking(conbination,nextdigit):
            # 终止条件
            if len(nextdigit)==0:
                res.append(conbination)
                return
            # 对 对应数字中的字母集合遍历
            for letter in phone[nextdigit[0]]:
                BackTracking(conbination+letter,nextdigit[1:])
        BackTracking('',digits)
        return res


队列

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:return []
        phone = ['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
        queue = [''] #初始化队列
        for digit in digits:
            for _ in range(len(queue)):
                tmp = queue.pop(0)
                for letter in phone[int(digit)-2]:
                    queue.append(tmp+letter)
        return queue


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值