代码随想录训练营第III期--025--python

第一题搞了半天,没弄清楚,自己写的就是不行,可能是回溯的退出机制没搞好,这个看起来比较清晰,就抄了这个答案

# 代码随想录训练营第III期--025--python

# 216
class Solution:
    def combinationSum3(self, k: int, n: int):
        res = []
        def backtrack(num, ss, path):
            if ss == 0 and len(path) == k:
                res.append(path[:])
                return 
            if num == 10:
                return 
            if ss < 0 :
                return 
            if len(path) > k:
                return 
            backtrack(num + 1, ss - num, path + [num])
            backtrack(num + 1, ss, path)
        backtrack(1, n, [])
        return res 
k = 3
n = 7 
sl = Solution()
print(sl.combinationSum3(k,n))


# 017
    def letterCombinations(self, digits: str) -> List[str]:
        if digits == '': return []

        dd  ={'2':'abc','3':'def','4':'ghi','5':'jkl',
                '6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}

        res = []
        def backtrack(temp, i):
            if i == len(digits):
                res.append(temp)
                return 
            for a in dd[digits[i]]:
                backtrack(temp + a, i + 1)
        
        backtrack('', 0)
        
        return res 

你可能感兴趣的:(代码随想录,python,leetcode,开发语言)