前天开始突然阳了,休息了两天,今天不发烧了继续学习!
第一题
Find all valid combinations of
k
numbers that sum up ton
such that the following conditions are true:
- Only numbers
1
through9
are used.- Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
采用递归的方法,整体思路和前一道题 (LC 77)差不多。
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = [] # save results
self.backtracking(n, k, 0, 1, [], result)
return result
def backtracking(self, targetSum, k, currentSum, startIndex, path, result):
if currentSum > targetSum:
return
if len(path) == k:
if currentSum == targetSum:
result.append(path[:])
return
for i in range(startIndex, 9 - (k - len(path)) + 2):
currentSum += i
path.append(i)
self.backtracking(targetSum, k, currentSum, i + 1, path, result)
currentSum -= i
path.pop()
第二题
17. Letter Combinations of a Phone Number
Given a string containing digits from
2-9
inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
感觉这道题有点实际用途,但是想一想本质,还是递归的解法
class Solution:
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):
if len(digits) == 0:
return self.result
self.backtracking(digits, 0)
return self.result