150强访谈简单

组合总和

“组合和”问题的详细指南和 Python 实现。

问题陈述

简单

给定一组不同的候选整数和一个目标整数目标,返回候选数的所有唯一组合的列表,其中所选数字之和等于目标。您可以按任何顺序返回组合。

可以从候选人中无限次地选择相同的号码。如果至少一个所选数字的频率不同,则两个组合是唯一的。

实现函数 combinationSum(candidates: list, target: int) -> list

约束条件
  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct
  • 1 <= target <= 40

示例

Example 1
Input
[2,3,6,7], 7
Output
[[2,2,3],[7]]
Explanation

2 + 2 + 3 = 7 and 7 = 7. These are the only two combinations.

Example 2
Input
[2,3,5], 8
Output
[[2,2,2,2],[2,3,3],[3,5]]
Explanation

2+2+2+2 = 8, 2+3+3 = 8, and 3+5 = 8.

Example 3
Input
[2], 1
Output
[]
Explanation

No combination of 2's can sum to 1.

Need a Hint?
考虑使用回溯特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。