216.组合总和III

  1. 回溯,照猫画虎根据77写的回溯,剪纸还是有点没搞清楚。先这样吧。。。
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        # 只用数字1-9,遍历k遍
        self.res = []
        self.backtracking(k,n,1,[])
        return self.res

    def backtracking(self, k, n, start_index, path):
        print(k, n, start_index, path)
        if k < 0 or n < 0: return

        if k == 0 and n == 0:
            self.res.append(path[:])
            return 

        for i in range(start_index, 10):
            path.append(i)
            self.backtracking(k-1, n-i, i+1, path)
            path.pop()

17.电话号码的字母组合

  1. 感觉套路和之前几题差不多
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        self.res = []
        self.map = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', 
        '7':'pqrs', '8':'tuv', '9':'wxyz'}
        if len(digits) == 0: return self.res

        self.backtracking(digits, 0, [])
        return self.res
        
    def backtracking(self, digits, index, path):
        if len(digits) <= index:
            self.res.append("".join(path[:]))
            return 

        digit = digits[index]
        for i in self.map[digit]:
            path.append(i)
            self.backtracking(digits, index+1, path)
            path.pop()

01-31 14:24