classSolution:defcombinationSum3(self, k:int, n:int)-> List[List[int]]:
ans =[]defbt(node, ans_lis, temp_sum):if temp_sum > n:returnif temp_sum == n:iflen(ans_lis)== k:
ans.append(ans_lis)else:returnfor j inrange(node+1,10):
bt(j, ans_lis+[j], temp_sum+j)if temp_sum+j > n:breakfor i inrange(1,10):
bt(i,[i], i)return ans
17. 电话号码的字母组合:
代码思路
classSolution:defletterCombinations(self, digits:str)-> List[str]:if digits =="":return[]
dic ={"2":'abc',"3":'def',"4":'ghi',"5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
ans =[]
digits_list =list(digits)defbt(digit_index, ans_lis):iflen(ans_lis)==len(digits):
ans.append("".join(ans_lis))returnfor j in dic[digits_list[digit_index+1]]:
bt(digit_index+1, ans_lis+[j])for i in dic[digits_list[0]]:
bt(0,[i])return ans