216. Combination Sum III
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
result = []
self.backtracking(k,n,0,1,[],result)
return result
def backtracking(self, k, n, s, startIndex, path, result):
if s > n: #剪枝
return
if len(path) == k and s == n:
result.append(path[:])
return
for i in range(startIndex, 9 - (k - len(path)) + 2):
s += i
path.append(i)
self.backtracking(k,n,s,i+1, path, result)
s -= i
path.pop()
17. Letter Combinations of a Phone Number
class Solution(object):
def __init__(self):
self.letterMap = [
"", # 0
"", # 1
"abc", # 2
"def", # 3
"ghi", # 4
"jkl", # 5
"mno", # 6
"pqrs", # 7
"tuv", # 8
"wxyz" # 9
]
self.result = []
self.s = ""
def backtracking(self, digits, index):
if index == len(digits):
self.result.append(self.s)
return
digit = int(digits[index])
letters = self.letterMap[digit]
for i in range(len(letters)):
self.s += letters[i]
self.backtracking(digits,index+1)
self.s = self.s[:-1]
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits)==0:
return self.result
self.backtracking(digits, 0)
return self.result
注意backtracking传入的参数,数组和index, for loop是针对数组里的每一个数字