第77题. 组合
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
解决方法
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
def huisu(n,k,path,startindex):
if len(path)==k:
result.append(path[:])
return None
for i in range(startindex,n+1):
path.append(i)
huisu(n,k,path,i+1)
path.pop()
path,result=[],[]
huisu(n,k,path,1)
return result
216.组合总和III
找出所有相加之和为 n
的 k
个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
解决方法
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def huisu(n,k,path,startindex):
if sum(path)>n:
return None
if len(path)==k:
if sum(path)==n:
result.append(path[:])
return None
for i in range(startindex,10):
path.append(i)
huisu(n,k,path,i+1)
path.pop()
path,result=[],[]
huisu(n,k,path,1)
return result
17.电话号码的字母组合
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
解决方法
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 = []
def getCombinations(self, digits, index, s):
if index == len(digits):
self.result.append(s)
return
digit = int(digits[index])
letters = self.letterMap[digit]
for letter in letters:
self.getCombinations(digits, index + 1, s + letter)
def letterCombinations(self, digits):
if len(digits) == 0:
return self.result
self.getCombinations(digits, 0, "")
return self.result