Creative MATH front Page cover for notebook 📒 #shorts #maths #shortvideo #frontpage

Creative MATH front Page cover for notebook 📒 #shorts #maths #shortvideo #frontpage

AI-Generated Summary

Get# 1. 题目

216. 组合总和 III

找出所有相加之和为 nk 个数的组合,且满足下列条件:

  • 只使用数字1到9
  • 每个数字 最多使用一次

返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。

示例 3:

输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。

提示:

  • 2 <= k <= 9
  • 1 <= n <= 60

2. 思路

回溯法,使用startIndex来避免重复组合。当path的长度等于k时,判断path中元素之和是否等于n,如果等于则加入结果集。否则继续递归。

3. 代码

python
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
path = []
def backtracking(k, n, startIndex):
if len(path) == k:
if sum(path) == n:
res.append(path[:])
return
for i in range(startIndex, 10):
path.append(i)
backtracking(k, n, i + 1)
path.pop()
backtracking(k, n, 1)
return res

📜 Full Transcript

[Music] And if you hear the sound like your back knees, baby shake it to the max. Please turn up the base to the max. Please just rewind. Let me shake it to the max. Take it to the max. Take it to the man. Take it to the [Music] shad. Love. Yeah. Yeah. [Music]

[ad_1]
[ad_2]