代码随想录算法训练营第二十九天 | 216.组合总和III,17.电话号码的字母组合

216.组合总和III

题目链接:216. 组合总和III
思路:终止条件的确定需要仔细思考,由于倒数第二个数确认后,最后一个数也随之确认,所以终止条件是 k == 1。其次不是每个终止条件所得到的结果都符合题目要求,因此需要增加判断n > ans[-1] and n < 10,在终止条件内处理完节点后别忘了撤销结果。

class Solution:
    def _combination_sum3(self, k: int, n: int, start: int, res: List[List[int]], ans: List[int]):
        if k == 1:
            if n > ans[-1] and n < 10:
                ans.append(n)
                res.append(ans.copy())
                ans.pop()
            return

        for i in range(start, 10):
            
            ans.append(i)
            self._combination_sum3(k-1, n - i, i + 1, res, ans)
            ans.pop()
    
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res = []
        self._combination_sum3(k, n, 1, res, [])
        return res

17.电话号码的字母组合

题目链接:17.电话号码的字母组合
思路:这题每个集合遍历的宽度不一样,一开始有点没转过弯来。不过完全能用回溯模板来套,只不过需要自行构造不等长的横向遍历

class Solution:
    def _letter_combinations(self, digits: str, index: int, num_letter_map: Dict[str, str], res: List[str], ans: str):
        if index == len(digits):
            res.append(ans)
            return

        for char in num_letter_map[digits[index]]:
            ans += char
            self._letter_combinations(digits, index + 1, num_letter_map, res, ans)
            ans = ans[:-1]

    def letterCombinations(self, digits: str) -> List[str]:
        res = []
        if digits:
            num_letter_map = {
                "2": "abc", "3": "def",
                "4" : "ghi", "5": "jkl", "6": "mno",
                "7": "pqrs", "8": "tuv", "9": "wxyz"
            }
            self._letter_combinations(digits, 0, num_letter_map, res, "")
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值