77. Combinations
题目大意
Given two integers n
and k
, return all possible combinations of k
numbers chosen from the range [1, n].
You may return the answer in any order.
中文释义
给定两个整数 n
和 k
,返回从范围 [1, n] 中选择的所有可能的 k
个数字的组合。
答案可以以任何顺序返回。
示例
示例 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
示例 2:
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.
限制条件
1 <= n <= 20
1 <= k <= n
解题思路
目标是生成从1到n的数字中选择k个数字的所有组合。使用深度优先搜索(DFS)算法来生成组合。通过递归的方式,不断选择数字,并将它们添加到临时组合中,直到达到了选择的数量k,然后将该组合添加到结果集中。接着,回溯到上一步,继续选择下一个数字,直到遍历完所有可能的数字。
步骤说明
下面是生成组合的具体步骤:
-
创建一个类Solution,其中包含公共变量:
ans
:用于存储最终的组合结果,初始