Programming Camp – Algorithm Training Camp – Day 25

1. Combination Sum III (Leetcode Number: 669)

a. WITHOUT OPTIMIZATION: Compared with problem 77, the condition to stop the recursion needs to be revised as the given numbers are clearly declared and sit between 1 to 9.

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res = []
        sub_res = []
        
        def backtracking(n, k, st_id):
            if sum(sub_res) == n and len(sub_res) == k:
                res.append(sub_res[:])
                return
            
            for i in range(st_id, 10):
                sub_res.append(i)
                backtracking(n, k, i + 1)
                sub_res.pop()
            
        
        backtracking(n, k, 1)
        return res

b. WITH OPTIMIZATION: If the sum of sub_res is bigger than n, the current recursion could be skipped. 

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        res = []
        sub_res = []
        
        def backtracking(n, k, st_id):
            if sum(sub_res) == n and len(sub_res) == k:
                res.append(sub_res[:])
                return
            if sum(sub_res) > n:
                return
            
            for i in range(st_id, 10):
                sub_res.append(i)
                backtracking(n, k, i + 1)
                sub_res.pop()
            
        
        backtracking(n, k, 1)
        return res

2. Letter Combinations of a Phone Number (Leetcode Number: 669)

In this case dictionary is used as the input number has been mapped to a few letters. The inputs of backtracking function here are the index of the original input string digits and a string of potential combinations.

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        res = []
        digits_li = list(digits)
        
        if len(digits) == 0:
            return []
        
        num_map = {
            '2' : 'abc',
            '3' : 'def',
            '4' : 'ghi',
            '5' : 'jkl',
            '6' : 'mno',
            '7' : 'pqrs',
            '8' : 'tuv',
            '9' : 'wxyz'
        }
        
        def backtracking(i, sub_res):
            if len(sub_res) == len(digits):
                res.append(''.join(sub_res))
                return
            
            letter_list = num_map[digits[i]]
            for letter in letter_list:
                sub_res.append(letter)
                backtracking(i + 1, sub_res)
                sub_res.pop()
        
        backtracking(0, [])
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值