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

76 阅读1分钟

216. 组合总和 III

代码随想录文章讲解

回溯+剪枝

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        path = []
        res = []
​
        def _backtracking(k, n, path_sum, num):
            nonlocal path
            nonlocal res
​
            # if sum(path) > n, we do not need to search anymore
            if path_sum > n:
                return
​
            if len(path) == k:
                if sum(path) == n:
                    res.append(path[:])
                return
​
            # if there are no more than k - len(path) nums remain, we cannot find the solution in this recursion
            # i is the start index
            for i in range(num, 10 - (k - len(path)) + 1):
                path.append(i)
                _backtracking(k, n, path_sum + i, i+1)
                path.pop()
​
        _backtracking(k, n, 0, 1)
​
        return res

17. 电话号码的字母组合

代码随想录文章讲解

回溯法

# Time complexity: O(4^N·N)
# Space complexity: O(N)
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
​
        nums_letter_map = {
            '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']
        }
​
        letter_comb = ''
        res = []
​
        def _backtracking(n, idx):
            nonlocal letter_comb
            nonlocal res
            nonlocal nums_letter_map
            nonlocal digits
​
            if len(letter_comb) == n:
                res.append(letter_comb)
                return
​
            d = digits[idx]
            for l in nums_letter_map[d]:
                letter_comb += l
                _backtracking(n, idx + 1)
                letter_comb = letter_comb[:-1]
​
        _backtracking(len(digits), 0)
        return res