【LeetCode 面试经典150题】77. Combinations 组合

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.

中文释义

给定两个整数 nk,返回从范围 [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,然后将该组合添加到结果集中。接着,回溯到上一步,继续选择下一个数字,直到遍历完所有可能的数字。

步骤说明

下面是生成组合的具体步骤:

  1. 创建一个类Solution,其中包含公共变量:

    • ans:用于存储最终的组合结果,初始
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值