Given two integers n and k, return all possible combinations ofknumbers chosen from the range[1, n].
You may return the answer in any order.
Example 1:
1 2 3 4
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.
Example 2:
1 2 3
Input: n = 1, k = 1 Output: [[1]] Explanation: There is 1 choose 1 = 1 total combination.
题目大意
给定两个整数 n 和 k,从范围 [1, n] 中选择 k 个数字,返回所有可能的组合。组合是无序的(例如 [1,2] 和 [2,1] 视为同一种组合),结果顺序可任意。
例如:
输入 n=4, k=2,输出 [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]](共 6 种组合,即组合数 C (4,2)=6);
输入 n=1, k=1,输出 [[1]](仅 1 种组合)。
解题思路
该问题的核心是从 [1, n] 中选择 k 个数字,生成所有可能的无序组合。解题思路基于递归回溯和剪枝优化,具体如下:
倒序枚举与选 / 不选决策 从数字 n 开始倒序枚举(从大到小),每个数字有两种选择:
选当前数字:将其加入临时组合,递归处理下一个更小的数字(确保组合内数字无序且不重复);
不选当前数字:直接递归处理下一个更小的数字。
终止条件 当临时组合的长度达到 k 时,将其加入结果列表,结束当前递归。
剪枝优化 若不选当前数字 i,需保证剩余数字(i-1 个)足够填满组合(还需选 d 个,d = k - 当前组合长度)。仅当 i > d 时(即剩余数字 ≥ 所需数字),才考虑不选 i,否则直接跳过(避免无效搜索)。