216.组合总和III
思路
思路和77、组合非常相似。
剪枝
两处剪枝
- 如果已存的数组的和大于
n
,就没有继续遍历的必要了 k
的个数,如果继续向下遍历不能得到k
个数字,停止遍历。
代码
原始
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
path = []
def helper(startIndex, k, n):
if len(path) == k and sum(path) == n:
res.append(path.copy())
return
for i in range(startIndex, 10):
path.append(i)
helper(i+1, k, n)
path.pop()
helper(1, k, n)
return res
剪枝过后
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
path = []
def helper(startIndex, k, n):
if len(path) == k and sum(path) == n:
res.append(path.copy())
return
# 剪枝1
if sum(path) > n:
return
# 剪枝2
for i in range(startIndex, 9 - (k-len(path)) + 2):
path.append(i)
helper(i+1, k, n)
path.pop()
helper(1, k, n)
return res
复杂度分析
- 时间复杂度:
O(n * 2^n)
,横向1到9每个数字可取可不取,为2^n。纵向可进行n次如此的操作。 - 空间复杂度:
O(n)
17.电话号码的字母组合
思路
这道题和组合问题不同的地方在于,每次遍历的时候,for循环的元素是不一样的。本题每一个数字代表的是不同集合,也就是求不同集合之间的组合。所以在递归的时候,我们传递的是一个index,帮助定位到digits的下一位,我们在递归的函数里面再找到对应的字符集。
代码
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
digToChar = {"2": "abc",
"3": "def", "4": "ghi", "5": "jkl", "6": "mno",
"7": "pqrs", "8":"tuv", "9":"wxyz"}
res = []
path = []
if not digits:
return res
def helper(startIndex):
if len(path) == len(digits):
res.append("".join(path))
if startIndex >= len(digits):
return
digit = digits[startIndex]
letters = digToChar[digit]
for letter in letters:
path.append(letter)
helper(startIndex+1)
path.pop()
helper(0)
return res
复杂度分析
- 时间复杂度:
O(3^m * 4^n)
,其中m
是对应四个字母的数字个数,n
是对应三个字母的数字个数 - 空间复杂度:
O(3^m * 4^n)